Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 合并具有相同键但不同值的dict_Python_List_Dictionary_Merge - Fatal编程技术网

Python 合并具有相同键但不同值的dict

Python 合并具有相同键但不同值的dict,python,list,dictionary,merge,Python,List,Dictionary,Merge,一般来说,我对python和开发相当陌生,所以我确信我的问题措辞有点错误。英语也不是我的第一语言,所以如果你想了解更多关于我想做什么的信息,我很乐意解释 基本上,我有一个字典列表,它们共享相同的键但值不同。 例如: List1 = [{ 'name':'yuval', 'age':16, 'favorite_thing_to_do': 'playing the cello' }, { 'name':'yuval', 'age':16, 'favorite_thing_to_do':'hear

一般来说,我对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'}]
我要查找的输出是一个列表,其中可以将
最喜欢的东西\u to\u 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\u dict
的函数,它基本上使用两个字典,比较前两个键(name和age),如果值相同,它将返回一个字典,其中
favorite\u thing\u to\u do
是函数接收的两个不同字典中不同值的列表

作为一个概念,功能非常有效;但是,我不知道如何在包含100多个未筛选字典的列表上运行此函数; 有没有更简单的方法

编辑: 我将包括到目前为止我所做的相关代码。 我不知道如何在列表中执行我想要的操作,所以我只声明了两个字典:Item3,Item4,我的函数merge\u 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']}

我发现我错过了名字和年龄部分。这是一个变体,其中我使用name和age的元组作为键,dict作为值

编辑后以所要求的格式显示结果(不过最好只返回名称):


我发现我错过了名字和年龄部分。这是一个变体,其中我使用name和age的元组作为键,dict作为值

编辑后以所要求的格式显示结果(不过最好只返回名称):


你可以这样做:

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'}]


def merge_dict(dictionary,merged_dict):
    name = dictionary.get('name')
    age = dictionary.get('age')
    favorite = dictionary.get('favorite_thing_to_do')

    #var to inform if needed to write a new dict:
    found_item = False

    # if merged_dict list is empty create the first dict:
    if len(merged_dict)==0:
        merged_dict.append({'name':name, 'age':age,'favorite_thing_to_do':[favorite] })

    # if  merged_dict list is not empty,
    else:
        #look for name and age in all dicts of merged_dict:
        for registred_dict in merged_dict:
            #If found => Append favorite_thing_to_do
            if registred_dict.get('name') == name and registred_dict.get('age')==age:
                registred_dict['favorite_thing_to_do'].append(favorite)
                found_item=True

        #If not found create a new dict in merged_dict:
        if not found_item:
            merged_dict.append({'name':name, 'age':age,'favorite_thing_to_do':[favorite] })


merged_dict = []
for dictionary in List1:
    merge_dict(dictionary,merged_dict)
print(merged_dict)

Item4 = {
'name':'shiri',
'age':12,
'favorite_thing_to_do': 'listening to teachers'
 }
merge_dict(Item4,merged_dict)
print(merged_dict)
结果第一次打印:

[{'name': 'yuval', 'age': 16, 'favorite_thing_to_do': ['playing the cello', 'hearing music']}, {'name': 'shiri', 'age': 12, 'favorite_thing_to_do': ['watch TV']}]
合并项目4后的结果:

[{'name': 'yuval', 'age': 16, 'favorite_thing_to_do': ['playing the cello', 'hearing music']}, {'name': 'shiri', 'age': 12, 'favorite_thing_to_do': ['watch TV', 'listening to teachers']}]

你可以这样做:

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'}]


def merge_dict(dictionary,merged_dict):
    name = dictionary.get('name')
    age = dictionary.get('age')
    favorite = dictionary.get('favorite_thing_to_do')

    #var to inform if needed to write a new dict:
    found_item = False

    # if merged_dict list is empty create the first dict:
    if len(merged_dict)==0:
        merged_dict.append({'name':name, 'age':age,'favorite_thing_to_do':[favorite] })

    # if  merged_dict list is not empty,
    else:
        #look for name and age in all dicts of merged_dict:
        for registred_dict in merged_dict:
            #If found => Append favorite_thing_to_do
            if registred_dict.get('name') == name and registred_dict.get('age')==age:
                registred_dict['favorite_thing_to_do'].append(favorite)
                found_item=True

        #If not found create a new dict in merged_dict:
        if not found_item:
            merged_dict.append({'name':name, 'age':age,'favorite_thing_to_do':[favorite] })


merged_dict = []
for dictionary in List1:
    merge_dict(dictionary,merged_dict)
print(merged_dict)

Item4 = {
'name':'shiri',
'age':12,
'favorite_thing_to_do': 'listening to teachers'
 }
merge_dict(Item4,merged_dict)
print(merged_dict)
结果第一次打印:

[{'name': 'yuval', 'age': 16, 'favorite_thing_to_do': ['playing the cello', 'hearing music']}, {'name': 'shiri', 'age': 12, 'favorite_thing_to_do': ['watch TV']}]
合并项目4后的结果:

[{'name': 'yuval', 'age': 16, 'favorite_thing_to_do': ['playing the cello', 'hearing music']}, {'name': 'shiri', 'age': 12, 'favorite_thing_to_do': ['watch TV', 'listening to teachers']}]

你能展示一下你到目前为止试过的代码吗。我要更新帖子。你能展示一下你到目前为止试过的代码吗?当然。我将更新帖子。谢谢你的回答!我对它进行了测试,它似乎大部分都有效。请注意,如果将来有人要使用它,当您声明result[k]=list(result[k])时,它可能会导致一个只有一个值的列表。因此,我添加了一个if语句——“if len(result[k])==1:result[k]=result[k][0]”。这似乎解决了列表长度为1的问题,使代码看起来更漂亮、更清晰。谢谢你的回答!我对它进行了测试,它似乎大部分都有效。请注意,如果将来有人要使用它,当您声明result[k]=list(result[k])时,它可能会导致一个只有一个值的列表。因此,我添加了一个if语句——“if len(result[k])==1:result[k]=result[k][0]”。这似乎解决了列表长度为1的问题,使代码看起来更漂亮、更清晰。