Python - 从嵌套的dicitonary获取值

时间:2016-11-10 17:46:09

标签: python dictionary

如何构建for loop以便在此嵌套float中为所有dictionary打印所有user值?

   plist = {'user1': {u'Fake Plastic Trees': 1.0, u'The Numbers': 1.0, u'Videotape': 1.0}}

所需输出= [1.0, 1.0, 1.0]

2 个答案:

答案 0 :(得分:0)

有一种dict.values()方法可以完全满足您的需求。

a_dict = {'user1': {u'Fake Plastic Trees': 1.0, u'The Numbers': 1.0, u'Videotape': 1.0}}
first_key = list(a_dict.keys())[0]
values = a_dict[first_key].values()
print(list(values))

输出

[1.0, 1.0, 1.0]

编辑:如果你想返回问题评论中提到的所有键的所有值的一个扁平列表,你可以这样做:

a_dict = {
    'user1': {u'Fake Plastic Trees': 1.0, u'The Numbers': 2.0, u'Videotape': 3.0},
    'user2': {u'Foo': 4.0, u'Bar': 5.0},
}
values = []
for k in a_dict.keys():
    for v in a_dict[k].values():
        values.append(v)
print(values)

输出

[4.0, 5.0, 3.0, 1.0, 2.0]

答案 1 :(得分:0)

使用dict.values()获取您想要的行为。

   >>> plist = {'playlist': {u'Fake Plastic Trees': 1.0, u'The Numbers': 1.0, u'Videotape': 1.0}}
    >>> list(plist['playlist'].values())
    [1.0, 1.0, 1.0]
    >>> 
相关问题