Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

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)

Solution 2:

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.

Post a Comment for "Merging Different Keys Inside A List Of Dictionaries"