1
votes

Nested dictionary has a length of 12, this is one of the records:

{('ALEXANDER', 'MALE'): {'2010': ('2619', None), '2011': ('2494', None), '2009': ('2905', None)}, ...

Main key = ('ALEXANDER', 'MALE')

Main value (which is nested dictionary) = {'2010': ('2619', None), '2011': ('2494', None), '2009': ('2905', None)}

Nested dictionary key/value = '2010': ('2619', None) ...

How would one access the year '2010' and the value '2619'?

Is it possible to do this using variables?

4
What's your expected output? - Avinash Raj
Hi, One of the expected outputs is to rank the names according to the year and count, (count = '2619' in the example). The "None" would become a rank like (1 , 2, 3 ...) - Greg

4 Answers

1
votes

This may point you in the right direction:

>>> d= {('ALEXANDER', 'MALE'): {'2010': ('2619', None), '2011': ('2494', None), '2009': ('2905', None)}}
>>> for mainKey in d:
    print(mainKey)
    for key,val in d[mainKey].items():
        print(key,val[0])


('ALEXANDER', 'MALE')
2011 2494
2009 2905
2010 2619
2
votes

If D = {'2010': ('2619', None), '2011': ('2494', None), '2009': ('2905', None)}

Then D.keys() return the list of keys in the dictionary ['2009', '2011', '2010']

Then you can access to the value 2010 by D.keys()[-1] and to 2619 by D[D.keys()[-1]][0]

0
votes
data = {
    ('ALEXANDER', 'MALE'): {'2010': ('2619', None), '2011': ('2494', None), '2009': ('2905', None)},
    # ...
}
value, _ = data[('ALEXANDER', 'MALE')]['2010']

Then value = '2619'

0
votes

When your dictionary's key is a tuple, I personally prefer to use the namedTuple function. This allows you access elements in the dictionary in a clean and readable way.

In the code below I present a way to use the namedTuple construct and some ways to access the elements further.

from collections import namedtuple

my_dict = {('ALEXANDER', 'MALE'): {'2010': ('2619', None), '2011': ('2494', None), '2009': ('2905', None)}}

person = namedtuple("Person", ["name", "sex"])
nt1 = person(name="ALEXANDER", sex="MALE")
print nt1.name
# outputs "ALEXANDER"
print nt1.sex
# outputs "MALE"
print my_dict[nt1]
# outputs {'2009': ('2905', None), '2011': ('2494', None), '2010': ('2619', None)}
print my_dict[nt1].keys()
# outputs ['2009', '2011', '2010']
print my_dict[nt1]['2010']
# outputs ('2619', None)
print my_dict[nt1]['2010'][0]
# outputs 2619