user2962024
user2962024

Reputation: 317

Merging different keys inside a list of dictionaries

I apologize in advance if this is a repeated question, I tried very hard to find it in Stack Overflow, but I was not successful. I have a list of dictionaries like the one bellow.

d1 = {'saw': ['movie', '14', 'bird', '8', 'light', '5', 'plane', '4', 'man', '4'], 
'saw': ['zit', '10', 'popcorn', '6', 'pimple', '6', 'cherry', '5', 'pill', '4'],
'evicted': ['tenant', '66', 'family', '5', 'renter', '5', 'neighbor', '4'], 
'evicted': ['dog', '9', 'teacher', '9', 'neighbor', '7', 'man', '6', 'girl', '6']}

I would like to merge different items,base on their key. So that they look like:

d2 = {'saw': ['movie', '14', 'bird', '8', 'light', '5', 
'plane', '4', 'man', '4', 'zit', '10', 'popcorn', '6', 'pimple', '6', 
'cherry', '5', 'pill', '4'],
'evicted': ['tenant', '66', 'family', '5', 'renter', '5', 'neighbor', '4', 
'dog', '9', 'teacher', '9', 'neighbor', '7', 'man', '6', 'girl', '6']}

I am using this code, but it I am not having the desired the output:

d2 = {}
for d in d1:
    for k, v in d1 ():
        if k not in d2: d2 [k] = []
        d2 [k].append (v)
print(d2)

I guess this works better when there are two separate lists of dictionaries to merge. How to merge different keys inside a list? I really appreciate any help on this!

Upvotes: 0

Views: 106

Answers (2)

Luyi Tian
Luyi Tian

Reputation: 371

1.if your d1 is a list it's ok. But if your d1 is a dict, dict cannot have duplicate keys. it is the basic proporty of dict. so your d1 is illegal, will only have one evicted/saw

2 assume d1 is a list the codes are:

for dicts in d1:
   for key, value in dicts.items():
      new_dict.setdefault(key,[]).extend(value)

Upvotes: 1

Ethan Furman
Ethan Furman

Reputation: 69288

The problem is that a dictionary cannot have duplicate keys. If you add a print d1 after you declare it you will see that the duplicate keys are gone. You need to either use separate dictionaries, or some other data structure for d1.

Upvotes: 0

Related Questions