gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:29:06 24 4
gpt4 key购买 nike

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

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))

字典通常要长得多,包含字符串、 bool 值、整数和 float 。
当我尝试我的函数时,它说 AttributeError: 'str' object has no attribute 'items'

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

最佳答案

你可以尝试:

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 字典没有顺序,因此值列表中的顺序与您提供给它的字典具有相同的无意义顺序。

关于python - 从嵌套字典中获取值到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32643586/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com