Accessing values in nested dictionary

偶尔善良 提交于 2019-12-17 23:44:28

问题


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?


回答1:


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:


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]




回答3:


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

Then value = '2619'




回答4:


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


来源:https://stackoverflow.com/questions/33747234/accessing-values-in-nested-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!