gpt4 book ai didi

python - 合并到不同的词典

转载 作者:行者123 更新时间:2023-11-28 20:18:19 24 4
gpt4 key购买 nike

我有两个这样的字典列表:

dic1 = [{'Age': 8, 'Pets Name': 'Felix', 'Species': 'Cat'}, {'Age': 57, 'Pets Name': 'Michelangelo', 'Species': 'Tortoise'}, {'Age': 12, 'Pets Name': 'Rantanplan', 'Species': 'Dog'}, {'Age': '2', 'Pets Name': 'Nemo', 'Species': 'Fish'}, {'Age': '45', 'Pets Name': 'Leonardo', 'Species': 'Tortoise'}, {'Age': 9, 'Pets Name': 'Milo', 'Species': 'Dog'}, {'Age': 57, 'Pets Name': 'Raphael', 'Species': 'Tortoise'}, {'Age': '4', 'Pets Name': 'Dory', 'Species': 'Fish'}]
dic2 = [{'Pets Names': 'Michelangelo', "Owner's Names": 'Ana'}, {'Pets Names': 'Dory', "Owner's Names": 'Eva'}, {'Pets Names': 'Rantanplan', "Owner's Names": 'Ada'}, {'Pets Names': 'Leonardo', "Owner's Names": 'Ana'}, {'Pets Names': 'Felix', "Owner's Names": 'Eva'}, {'Pets Names': 'Raphael', "Owner's Names": 'Ana'}, {'Pets Names': 'Nemo', "Owner's Names": 'Eva'}]

我需要制作第三个字典列表,作为(字典的)键,主人的名字,以及他们各自宠物的年龄值。例如,给定上面的两个列表,输出应该是:

dic3 = [{'Ana': [57, 45, 57]}, {'Eva': [4, 8, 2]}, {'Ada': [12]}]

主要目标是获取每个主人的宠物年龄的平均值,但我认为我可以在获得所需的指令后自己完成。到目前为止我只有这个:

def merge_dicts(dic1,dic2):

name = [li['Pets Name'] for li in dic1]
age = [li['Age'] for li in dic1]
owenrsName = [li["Owner's Names"] for li in dic2]

这为我提供了宠物名称、年龄和主人姓名的列表,但我不知道它是否与最终功能相​​关。

提前致谢。

最佳答案

dic1 = [{'Age': 8, 'Pets Name': 'Felix', 'Species': 'Cat'}, {'Age': 57, 'Pets Name': 'Michelangelo', 'Species': 'Tortoise'}, {'Age': 12, 'Pets Name': 'Rantanplan', 'Species': 'Dog'}, {'Age': '2', 'Pets Name': 'Nemo', 'Species': 'Fish'}, {'Age': '45', 'Pets Name': 'Leonardo', 'Species': 'Tortoise'}, {'Age': 9, 'Pets Name': 'Milo', 'Species': 'Dog'}, {'Age': 57, 'Pets Name': 'Raphael', 'Species': 'Tortoise'}, {'Age': '4', 'Pets Name': 'Dory', 'Species': 'Fish'}]
dic2 = [{'Pets Names': 'Michelangelo', "Owner's Names": 'Ana'}, {'Pets Names': 'Dory', "Owner's Names": 'Eva'}, {'Pets Names': 'Rantanplan', "Owner's Names": 'Ada'}, {'Pets Names': 'Leonardo', "Owner's Names": 'Ana'}, {'Pets Names': 'Felix', "Owner's Names": 'Eva'}, {'Pets Names': 'Raphael', "Owner's Names": 'Ana'}, {'Pets Names': 'Nemo', "Owner's Names": 'Eva'}]



def merge_dicts(dic1,dic2):
dict3= {}
result = []
name = [li['Pets Name'] for li in dic1]
age = [li['Age'] for li in dic1]
owenrsName = [li["Owner's Names"] for li in dic2]


for d2 in dic2:

pname = d2['Pets Names']
oname = d2["Owner's Names"]

if oname not in dict3:
dict3[oname] = []

for d1 in dic1:
if d1['Pets Name'] == pname:
dict3[oname].append(d1['Age'])
for key,value in dict3.items():
result.append({key:value})

print(result)


merge_dicts(dic1,dic2)

对/对

[{'Ada': [12]}, {'Eva': ['4', 8, '2']}, {'Ana': [57, '45', 57]}]

关于python - 合并到不同的词典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36936659/

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