从嵌套字典中获取值.Python

时间:2019-10-30 23:10:14

标签: python list 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)

我的结果:

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

但我希望列表为:

[0.3,0.4,0.8,0.95]

3 个答案:

答案 0 :(得分:2)

您可以对dict s的值简单地使用双重理解(相当于嵌套循环):

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]

答案 1 :(得分:1)

您需要再次遍历内部字典的值,并将每个值附加到输出变量。

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

答案 2 :(得分:0)

您可以这样做

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]