从嵌套字典中获取值到列表

时间:2015-09-18 03:54:08

标签: python

很奇怪,之前没有人问过这个问题。我无法在互联网上找到任何答案。我有一个嵌套的字典,我想要一个所有值的列表(不是嵌套列表)。这是我的代码:

dico = {
    "Balance": {
        "Normal": {
            "P1x": 0.889,
            "P1y": 700.0,
            "P2x": 0.889,
            "P2y": 884.0,
            "P3x": 1.028,
            "P3y": 1157.0,
            "P4x": 1.201,
            "P4y": 1157.0,
            "P5x": 1.201,
            "P5y": 700.0
        },
        "Utility": {
            "P1x": 0.889,
            "P1y": 700.0,
            "P2x": 0.889,
            "P2y": 884.0,
            "P3x": 0.947,
            "P3y": 998.0,
            "P4x": 1.028,
            "P4y": 998.0,
            "P5x": 1.028,
            "P5y": 700.0,
        }
    }
}

def grab_children(father):
    local_list = []
    for key, value in father.items():
        local_list.append(value)
        local_list.extend(grab_children(father[key]))
    return local_list

print(grab_children(dico))

这个词典通常要长得多,包含字符串,布尔,整数和浮点数 当我尝试我的功能时,它说AttributeError: 'str' object has no attribute 'items'

我理解为什么,但我不知道如何解决它...你能帮帮我吗? 谢谢!

2 个答案:

答案 0 :(得分:1)

def grab_children(father):
    local_list = []
    for key, value in father.items():
        local_list.append(key)
        local_list.append(value)
    return local_list
print(grab_children(dico))

答案 1 :(得分:1)

您可以尝试:

import collections

def walk(node):
    for key, item in node.items():
        if isinstance(item, collections.Mapping):
            print(key)
            walk(item)
        else:
            print('\t',key, item)

用你的例子,打印:

Balance
Utility
     P3y 998.0
     P1x 0.889
     P5x 1.028
     P5y 700.0
     P2x 0.889
     P1y 700.0
     P2y 884.0
     P4x 1.028
     P3x 0.947
     P4y 998.0
Normal
     P3y 1157.0
     P1x 0.889
     P5x 1.201
     P5y 700.0
     P2x 0.889
     P1y 700.0
     P2y 884.0
     P4x 1.201
     P3x 1.028
     P4y 1157.0

在Python 3.3+下,你可以这样做:

def walk(node):
    for key, value in node.items():
        if isinstance(value, collections.Mapping):
            yield from walk(value)
        else:
            yield key, value 

>>> list(walk(dico))
[('P5y', 700.0), ('P2y', 884.0), ('P4y', 1157.0), ('P4x', 1.201), ('P1x', 0.889), ('P3y', 1157.0), ('P2x', 0.889), ('P1y', 700.0), ('P3x', 1.028), ('P5x', 1.201), ('P5y', 700.0), ('P2y', 884.0), ('P4y', 998.0), ('P4x', 1.028), ('P1x', 0.889), ('P3y', 998.0), ('P2x', 0.889), ('P1y', 700.0), ('P3x', 0.947), ('P5x', 1.028)]

然后,如果您只想要值:

def walk(node):
    for key, value in node.items():
        if isinstance(value, collections.Mapping):
            yield from walk(value)
        else:
            yield value    

>>> list(walk(dico))
[700.0, 0.889, 0.889, 998.0, 1.028, 0.947, 700.0, 884.0, 998.0, 1.028, 700.0, 0.889, 0.889, 1157.0, 1.201, 1.028, 700.0, 884.0, 1157.0, 1.201]

但请记住,Python dicts没有顺序,因此值列表中的顺序与您提供它的字典具有相同的无意义顺序。