python - 合并具有相同键但不同值的字典
问题描述
总的来说,我对 python 和开发很陌生,所以我确信我的问题措辞有点错误。英语也不是我的第一语言,所以如果你想了解更多关于我想做的事情的信息,我很乐意解释。
基本上,我有一个字典列表,它们都共享相同的键但不同的值。例如:
List1 = [{
'name':'yuval',
'age':16,
'favorite_thing_to_do': 'playing the cello' },
{
'name':'yuval',
'age':16,
'favorite_thing_to_do':'hearing music'},
'name':'shiri',
'age':12,
'favorite_thing_to_do':'watch TV'}]
我正在寻找的输出是一个列表,favorite_thing_to_do
它可以在任何地方合并。
例如,输出将是
[{'name':'yuval',
'age':16,
'favorite_thing_to_do': ['playing the cello' , 'hearing music']},
{'name':'shiri',
'age':12,
'favorite_thing_to_do':'watch TV'}]
但是,我不知道该怎么做。我设法定义了一个名为 的函数merge_dict
,它基本上需要两个字典,比较前两个键(姓名和年龄),如果值相同,它返回一个字典,其中favorite_thing_to_do
是两个不同字典中不同值的列表收到的功能。
作为一个概念,这个功能很好用;但是,我不知道如何在包含 100 多个未过滤字典的列表上运行此函数;有没有更简单的方法来做到这一点?
编辑: 我将包括到目前为止我已经完成的相关代码。我不知道如何在列表中做我想做的事,所以我只声明了两个字典:Item3、Item4,我的函数 merge_dict 集中了它们:
Item3 = {
'name':'shiri',
'age':12,
'favorite_thing_to_do':'watch TV'}
Item4 = {
'name':'shiri',
'age':12,
'favorite_thing_to_do': 'listening to teachers'
}
def merge_dict(dict1, dict2):
# we know that dict1 and dict2 are the same length, same keys.
dict3 = {}
for i in dict1:
if dict1[i] == dict2[i]:
dict3[i] = dict1[i]
if i == 'favorite_thing_to_do':
if isinstance(dict1[i], str) and isinstance(dict2[i],str) :
dict3[i] = [dict1[i] , dict2[i]]
if isinstance(dict1[i], list) and isinstance(dict2[i],str):
dict3[i] = dict1[i] + [dict2[i]]
if isinstance(dict1[i], str) and isinstance(dict2[i],list):
dict3[i] = [dict1[i]] + dict1[i]
if isinstance(dict1[i], list) and isinstance(dict2[i],list):
dict3[i] = dict1[i] + dict1[i]
return dict3
print(merge_dict(Item3, Item4))
>>> {'name': 'shiri', 'age': 12, 'favorite_thing_to_do': ['watch TV',
'listening to teachers']}
解决方案
我看到我错过了名字和年龄部分。这是一个变体,其中我使用名称和年龄的元组作为键,使用字典作为值。
编辑为以要求的格式显示结果(尽管只返回名称可能会更好):
def merge(dirs):
names = {}
for d in dirs:
if (d['name'], d['age']) not in names:
names[(d['name'], d['age'])] = {}
for k in d:
if k not in ('name', 'age'):
if k not in names[(d['name'], d['age'])]:
names[(d['name'], d['age'])][k] = set([])
names[(d['name'], d['age'])][k].add(d[k])
# return names
return [{'name':k[0], 'age':k[1], 'favorite_things_to_do':
list(v2) } for k, v in names.items() for v2 in v.values() ]
print(merge(List1))
推荐阅读
- json - 在闭包中引用属性“_evolutionURL”需要明确的“自我”。使捕获语义明确
- vba - 无法使用 Excel VBA Selenium 登录
- spring - 使用 RedisTemplate 将不同的对象作为字符串迭代
- html - 我怎样才能延迟打字稿?
- laravel - Laravel如何在模型关系中获取id参数?
- javascript - 无法返回 JavaScript 嵌套回调函数内部函数返回值
- android - 当应用程序被杀死时,无头任务会自行杀死
- c++ - 我们如何在没有 stoi 命令的情况下将字符串转换为整数 / 以输入日期和输出整数
- php - PHP 图像无法正确显示
- java - 同步线程池ExecutorService