0

Trying to merge two or more dictionaries in python 2.7, However

**kwargs is not supported in python 2.7 it gives error like-Python version 2.7 does not support starred expressions in dicts .

is there any way to do it in python 2.7 ?

# Create first dictionary
dict1 = {  'Ritika': 5, 'Sam': 7, 'John' : 10 }
# Create second dictionary
dict2 = {'Aadi': 8,'Sam': 20,'Mark' : 11 }
# Create second dictionary
dict3 = {'x': 8,'y': 20,'z' : 11 }

dict4 = {**dict1 , **dict2, **dict3}
print dict4

Expected output-

{'Ritika': 5, 'Sam': 20, 'John': 10, 'Aadi': 8, 'Mark': 11, 'x': 8, 'y': 20, 'z': 11}
pkk
  • 379
  • 6
  • 18
  • 1
    Did you try this solution? with the copy? https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-taking-union-of-dictiona – Shai Aug 17 '21 at 05:55
  • @programandoconro, dictionaries cannot have duplicate keys. The last ```"sam"``` key is the one which has the value as 20. So ```"sam":20``` is taken –  Aug 17 '21 at 05:59
  • Given the solution for 2 dictionaries in the linked duplicate, it is enough to do: `merge_two_dicts(merge_two_dicts(x, y), z)`. – sophros Aug 17 '21 at 06:02
  • yes i tried it is working for only two dictionary @Shai – pkk Aug 17 '21 at 06:31
  • ignore duplicates no issues @Sujay – pkk Aug 17 '21 at 06:32
  • sorry i did't get you @sophros – pkk Aug 17 '21 at 06:33
  • Go check the [first answer](https://stackoverflow.com/a/26853961/6573902) to the linked question and use `mrge_two_dicts` from there. – sophros Aug 17 '21 at 06:47
  • I have tried that however it is working for only two dicts i want to do it for 3-4 dicts. @sophros I am able to do it in python 3 . but my question is for python 2.7. – pkk Aug 17 '21 at 06:54
  • 1
    It might sound stupid, but @sophros is kind of right in his way of "merge_two_dicts(merge_two_dicts(x, y), z)". What might help you is merge_many_dicts(myArrayOfDicts) Send an array of your dictionaries into this fuction and inside the function Iterate over them and insert them into a new dictionary with the copy() and update. This will create a totally new dictionary but it combines all of them – Shai Aug 18 '21 at 05:41

0 Answers0