简体   繁体   English

从嵌套字典中获取值。Python

[英]Get the value from a nested dictionary.Python

I want to get a list of the values from a nested dictionary.我想从嵌套字典中获取值列表。

d = {2.5: {2005: 0.3}, 2.6: {2005: 0.4}, 5.5: {2010: 0.8}, 7.5: {2010: 0.95}}

def get_values_from_nested_dict(dic):
    list_of_values = dic.values()
    l = []
    for i in list_of_values:
        a = i.values()
        l.append(a)
    return l

d1 = get_values_from_nested_dict(d)
print(d1)

My results:我的结果:

[dict_values([0.3]), dict_values([0.4]), dict_values([0.8]), dict_values([0.95])]

But I want the list to be:但我希望列表是:

[0.3,0.4,0.8,0.95]

You could simply use a double-comprehension (equivalent to a nested loop) on the dict s's values:您可以简单地对dict的值使用双重理解(相当于嵌套循环):

d = {2.5: {2005: 0.3}, 2.6: {2005: 0.4}, 5.5: {2010: 0.8}, 7.5: {2010: 0.95}}


[y for x in d.values() for y in x.values()]
# [0.3, 0.4, 0.8, 0.95]

You need to iterate again through the values of the internal dictionary and append each of them to the output variable.您需要再次遍历内部字典和 append 的值,它们每个都到 output 变量。

def get_values_from_nested_dict(dic):
    l = []
    for outer_value in dic.values():
        for value in outer_value.values():
            l.append(value)
    return l

You can do like this,你可以这样做,

In [97]: d                                                                                                                                                                                                  
Out[97]: {2.5: {2005: 0.3}, 2.6: {2005: 0.4}, 5.5: {2010: 0.8}, 7.5: {2010: 0.95}}

In [98]: list(map(lambda x:list(x.values())[0], d.values()))                                                                                                                                                
Out[98]: [0.3, 0.4, 0.8, 0.95]

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

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