我已经做了一些搜索,玩,但似乎仍然无法找到解决办法
假设我有一个字典列表,例如:
listofdicts = [
{'Name': 'Jim', 'Attribute': 'Height', 'Value': '6.3'},
{'Name': 'Jim', 'Attribute': 'Weight', 'Value': '170'},
{'Name': 'Mary', 'Attribute': 'Height', 'Value': '5.5'},
{'Name': 'Mary', 'Attribute': 'Weight', 'Value': '140'}
]
但我想把它们都放在单数命名的字典中,例如:
listofdicts = [
{'Person': {'Name': 'Jim', 'Attribute': 'Height', 'Value': '6.3'}},
{'Person': {'Name': 'Jim', 'Attribute': 'Weight', 'Value': '170'}},
{'Person': {'Name': 'Mary', 'Attribute': 'Height', 'Value': '5.5'}},
{'Person': {'Name': 'Mary', 'Attribute': 'Weight', 'Value': '140'}}
]
我该怎么做呢
我管理了以下内容,但它似乎只嵌套了一本字典:
betterlist = { 'Person' : i for i in listofdicts}
任何帮助都将不胜感激。谢谢大家
你很接近,你在创建一个列表理解,而不是字典理解
“它似乎只嵌套了一个字典”的原因是您的字典理解对每个元素使用相同的键,因此它用
i
的最新值覆盖以前的值所以基本上有两种(简单的)方法可以做到这一点
最清晰的方法是创建一个循环:
有一个快捷方式可以执行上述操作,称为
list comprehension
明白这只是一条捷径。没有任何性能改进。如果我是Python新手,我会选择第一种方法,因为我非常清楚它在做什么您几乎完全正确,但最外层的结构应该是一个列表
[]
,而您构造的每个元素都是您创建的字典{'Person': i}
:你写的东西叫做理解,只创建一本字典。由于字典中的键只能出现一次,因此每次迭代
i
都会覆盖单个键'Person'
,因此您的listofdicts
中恰好最后一个键相关问题 更多 >
编程相关推荐