How to merge multiple dicts with same key?

前端 未结 14 2537
别跟我提以往
别跟我提以往 2020-11-22 13:12

I have multiple dicts/key-value pairs like this:

d1 = {key1: x1, key2: y1}  
d2 = {key1: x2, key2: y2}  

I want the result to be a new di

14条回答
  •  臣服心动
    2020-11-22 13:40

    Assume that you have the list of ALL keys (you can get this list by iterating through all dictionaries and get their keys). Let's name it listKeys. Also:

    • listValues is the list of ALL values for a single key that you want to merge.
    • allDicts: all dictionaries that you want to merge.
    result = {}
    for k in listKeys:
        listValues = [] #we will convert it to tuple later, if you want.
        for d in allDicts:
           try:
                fileList.append(d[k]) #try to append more values to a single key
            except:
                pass
        if listValues: #if it is not empty
            result[k] = typle(listValues) #convert to tuple, add to new dictionary with key k
    

提交回复
热议问题