简体   繁体   English

访问嵌套字典中的值

[英]Accessing values in nested dictionary

Nested dictionary has a length of 12, this is one of the records: 嵌套字典的长度为12,这是记录之一:

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

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

Main value (which is nested dictionary) = {'2010': ('2619', None), '2011': ('2494', None), '2009': ('2905', None)} 主值(为嵌套字典)= {'2010': ('2619', None), '2011': ('2494', None), '2009': ('2905', None)}

Nested dictionary key/value = '2010': ('2619', None) ... 嵌套字典键/值= '2010': ('2619', None) ...

How would one access the year '2010' and the value '2619' ? 一个人如何获得'2010''2619'值?

Is it possible to do this using variables? 可以使用变量来做到这一点吗?

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

Then D.keys() return the list of keys in the dictionary ['2009', '2011', '2010'] 然后D.keys()返回字典中的键列表['2009', '2011', '2010']

Then you can access to the value 2010 by D.keys()[-1] and to 2619 by D[D.keys()[-1]][0] 然后,您可以通过D.keys()[-1]访问值2010 ,并通过D[D.keys()[-1]][0]访问值2619

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
data = {
    ('ALEXANDER', 'MALE'): {'2010': ('2619', None), '2011': ('2494', None), '2009': ('2905', None)},
    # ...
}
value, _ = data[('ALEXANDER', 'MALE')]['2010']

Then value = '2619' 然后value = '2619'

When your dictionary's key is a tuple, I personally prefer to use the namedTuple function. 当您的字典键是一个元组时,我个人更喜欢使用namedTuple函数。 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. 在下面的代码中,我介绍了一种使用namedTuple构造的方法以及一些进一步访问元素的方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM