[英]Extracting the values from nested dictionary in python
d= {0: {'Name': 'MN', 'volt': 1.0, 'an': 0.0},
1: {'Name': 'LT', 'volt': 1.0, 'an': 5.8},
2: {'Name': 'CK', 'volt': 1.0, 'an': 2.72},
3: {'Name': 'QL', 'volt': 1.0, 'an': 0.33}}
I am trying to create a matrix from the above nested dictionary that would result in the following output:我正在尝试从上面的嵌套字典创建一个矩阵,这将导致以下 output:
[MN 1.0 0.0
LT 1.0 5.8
CK 1.0 2.72
QL 1.0 0.33]
Using.values() function in python would result in the key names as well.在 python 中使用.values() function 也会产生键名。
I guess you can them in a list like this我想你可以在这样的列表中
>>> d = {0: {'Name': 'MN', 'volt': 1.0, 'an': 0.0},
1: {'Name': 'LT', 'volt': 1.0, 'an': 5.8},
2: {'Name': 'CK', 'volt': 1.0, 'an': 2.72},
3: {'Name': 'QL', 'volt': 1.0, 'an': 0.33}}
>>> [list(i.values()) for i in d.values()]
[['MN', 1.0, 0.0],
['LT', 1.0, 5.8],
['CK', 1.0, 2.72],
['QL', 1.0, 0.33]]
You iterate over the values of the outer dictionary and then again, extract the values of interior dictionaries via i.values
during iteration, store them in a list with list-comprehension.您迭代外部字典的值,然后再次在迭代期间通过
i.values
提取内部字典的值,将它们存储在具有列表理解的列表中。
If you want them flattened in a list如果您希望它们在列表中展平
>>> sum([list(i.values()) for i in d.values()], [])
['MN', 1.0, 0.0, 'LT', 1.0, 5.8, 'CK', 1.0, 2.72, 'QL', 1.0, 0.33]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.