从字典列表生成嵌套字典

2024-09-30 16:21:34 发布

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

我已经做了一些搜索,玩,但似乎仍然无法找到解决办法

假设我有一个字典列表,例如:

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}

任何帮助都将不胜感激。谢谢大家


Tags: name列表字典valueattribute命名personheight
3条回答

你很接近,你在创建一个列表理解,而不是字典理解

betterlist = [{ 'Person' : i} for i in listofdicts]

“它似乎只嵌套了一个字典”的原因是您的字典理解对每个元素使用相同的键,因此它用i的最新值覆盖以前的值

所以基本上有两种(简单的)方法可以做到这一点

最清晰的方法是创建一个循环:

newDict = []
for d in listofdicts:
    newDict.append({'Person': d}) # I'm creating the dict, and then appending to newDict

有一个快捷方式可以执行上述操作,称为list comprehension

newDict = [{'Person': d} for d in listofdicts] # Can you compare the 2 approach's syntax?

明白这只是一条捷径。没有任何性能改进。如果我是Python新手,我会选择第一种方法,因为我非常清楚它在做什么

您几乎完全正确,但最外层的结构应该是一个列表[],而您构造的每个元素都是您创建的字典{'Person': i}

better_list = [
    {'Person': p}
    for p in list_of_dicts
]

你写的东西叫做理解,只创建一本字典。由于字典中的键只能出现一次,因此每次迭代i都会覆盖单个键'Person',因此您的listofdicts中恰好最后一个键

相关问题 更多 >