Writing a table with values for several years as a dictionary?
<p>I have a table I want to write as a Python code, but I'm stuck and can't figure out how to do it.</p>

<p>I have a table with data for two years (1991 and 1992), and different values for each year (men: 35 (1991) and 42 (1992), women: 38 (1991), 39 (1992) and children: 15 (1991), 10 (1992).</p>

<p>What I want is to be able to write one variable (dictionary) in python that makes me able to search for a specific value in a specific year (ex: men(1992) = 42).</p>

<p>My best suggestion so far is to make a dictionary including tuples in something like this:</p>

<pre><code>people = {
    'year': (1991, 1992),
    'men': (35, 42),
    'women': (38, 39),
    'children': (15, 10)
    }
</code></pre>

<p>But this obviously not make it possible to search for both specific values in a specific year.</p>

<p>I suggest you put the dictionary in a custom class. This will give you a lot of flexibility regardless of how the data is laid-out in the dictionary itself because you can create methods to add, change, and delete entries in the table that will hide the details of the data structure. </p>

<p>For example, let's say you've decided to organized the data in the dictionary like this:</p>

<pre><code>{1991: {'men': 35, 'women': 38, 'children': 15},
 1992: {'men': 42, 'women': 39, 'children': 10}}
</code></pre>

<p>Then you could wrap that in a class like this:</p>

<pre><code>class People(object):
    def __init__(self):
        self._data = {}
    def add(self, year, men, women, children):
        self._data[year] = dict(men=men, women=women, children=children)
    def lookup(self, key, year):
        return self._data[year][key]
    def delete(self, year):
        del self._data[year]

people = People()
people.add(1991, 35, 38, 15)
people.add(1992, 42, 39, 10)

print(people.lookup('women', 1991))  # --&gt; 38
print(people.lookup('men', 1992))  # --&gt; 42
</code></pre>

python dictionary tuples