当前的问题包括将字典转换为列表。我无法将键和值对的特定值拆分为我想要的结果。
我有一本像这样的字典:
dict = [ {name:aa,age:12, id:121}, {name:bb,age:13, id:122},{name:cc,age:11, id:121}, {name:dd,age:15, id:122} ]
它有若干对键和值,其中最重要的是'ID'键。ID值是重复的所以我在寻找这个值的列表它看起来像这样:
121 = [
{name:aa,age:12},
{name:cc,age:11}
]
122 = [
{name:bb,age:13},
{name:dd,age:15}
]
我认为这应该很好,只是循环遍历子字典列表。
start_dict = [{'name':'aa','age':12,'id':121}, {'name':'bb','age':13,'id':122},{'name':'cc','age':11,'id':121}, {'name':'dd','age':15,'id':122}]
converted_dict = {}
for subdict in start_dict:
if subdict['id'] not in converted_dict:
converted_dict[subdict['id']] = [{k:v for k,v in subdict.items() if k != 'id'}]
else:
converted_dict[subdict['id']].append({k:v for k,v in subdict.items() if k != 'id'})
print(converted_dict)
{121: [{'name': 'aa', 'age': 12}, {'name': 'cc', 'age': 11}],
122: [{'name': 'bb', 'age': 13}, {'name': 'dd', 'age': 15}]}
from collections import defaultdict
start_dict = [
{'name': 'aa', 'age': 12, 'id': 121},
{'name': 'bb', 'age': 13, 'id': 122},
{'name': 'cc', 'age': 11, 'id': 121},
{'name': 'dd', 'age': 15, 'id': 122},
]
new_dict = defaultdict(list)
for entry in start_dict:
new_dict[entry["id"]].append(dict(name=entry["name"], age=entry["age"]))
print(dict(new_dict))