gpt4 book ai didi

python - 将值连接到列表中到 python 中的键

转载 作者:行者123 更新时间:2023-12-05 01:51:48 25 4
gpt4 key购买 nike

帮助我缩短代码并打印完全相同的输出,因为每次运行时键和值都可能不同。
这是输入字典:

personal_info_list = [
{"id": 1, "name": "John", "age": 32, "cars": "BMW"},
{"id": 1, "title": "engineer", "cars": "Mercedes", "phone": "samsung"},
{"id": 1, "cars": "Jaguar", "phone": "iphone"},
{"id": 2, "name": "Charlie", "age": 22, "phone": "iphone"},
{"id": 2, "title": "doctor", "cars": "BMW", "phone": "samsung"},
{"id": 3, "name": "Michael", "cars": "Volkswagen", "phone": "nokia"},
{"id": 3, "title": "doctor", "cars": "BMW", "phone": "samsung"},
]

输出字典应该是这样的:

{
1: {'name': 'John', 'age': 32, 'cars': ['BMW', 'Mercedes', 'Jaguar'], 'title': 'engineer', 'phone': ['samsung', 'iphone']},
2: {'name': 'Charlie', 'age': 22, 'phone': ['iphone', 'samsung'], 'title': 'doctor', 'cars': 'BMW'},
3: {'name': 'Michael', 'cars': ['Volkswagen', 'BMW'], 'phone': ['nokia', 'samsung'], 'title': 'doctor'}
}

我尝试了代码来获取 ID 的所有键并将其与其余的字典合并:

def formatDictionary(lst_1):
dict1={}
for i in lst_1:
for j in lst_1:
temp=[]
if i['id'] == j['id']:
for k,v in i.items():
S = Merge(i,j)
dict1[i['id']] = S
print(dict1)

formatDictionary(info_list)

这给了我如下输出:

{
1: {'id': 1, 'cars': 'Jaguar', 'phone': 'iphone'},
2: {'id': 2, 'title': 'doctor', 'cars': 'BMW', 'phone': 'samsung'},
3: {'id': 3, 'title': 'doctor', 'cars': 'BMW', 'phone': 'samsung'}
}

最佳答案

尝试使用 itertools.groupby 获取具有相同 id 的所有词典:

from itertools import groupby
from operator import itemgetter

result = {}
for personal_id, group in groupby(personal_info_list, itemgetter('id')):
result[personal_id] = {'id': personal_id}
for dct in group:
for k, v in dct.items():
if k != 'id':
if k in result[personal_id]:
if not isinstance(result[personal_id][k], list):
result[personal_id][k] = [result[personal_id][k]]
result[personal_id][k].append(v)
else:
result[personal_id][k] = v

这是结果的样子:

{1: {'age': 32,
'cars': ['BMW', 'Mercedes', 'Jaguar'],
'id': 1,
'name': 'John',
'phone': ['samsung', 'iphone'],
'title': 'engineer'},
2: {'age': 22,
'cars': 'BMW',
'id': 2,
'name': 'Charlie',
'phone': ['iphone', 'samsung'],
'title': 'doctor'},
3: {'cars': ['Volkswagen', 'BMW'],
'id': 3,
'name': 'Michael',
'phone': ['nokia', 'samsung'],
'title': 'doctor'}}

关于python - 将值连接到列表中到 python 中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71969880/

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