从嵌套字典获取值到lis

2024-04-20 02:49:08 发布

您现在位置:Python中文网/ 问答频道 /正文

很奇怪以前没人问这个。我在网上找不到任何答案。我有一个嵌套的dictionary,我想要一个所有it值的列表(不是嵌套列表)。这是我的密码:

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'

我知道为什么,但我不知道怎么解决。。。你能帮助我吗?
谢谢!你知道吗


Tags: 列表localdicolistgrabchildrenfatherp1x
2条回答
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))

您可以尝试:

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 dict没有顺序,因此值列表中的顺序与您输入的dict具有相同的无意义顺序。你知道吗

相关问题 更多 >