【发布时间】:2020-12-18 01:10:31
【问题描述】:
总的来说,我对 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']}
【问题讨论】:
-
你能显示你到目前为止尝试过的代码吗?
-
当然。我要更新帖子了。
标签: python list dictionary merge