4

I have an existing dictionary and I want to add a list of tuples into this dictionary.

Existing dictionary structure:

myD = {'key1': 123 , 'key2': 456}

List of tuples structure:

myL = [('fkey1',321),('fkey2',432),('fkey3',543)]

Expected dictionary after adding list of tuples

myD = {'key1': 123 ,'key2': 456 ,'fkey': 321 ,'fkey2': 432 ,'fkey3': 543}

How can I implement this in python?

Malintha
  • 4,512
  • 9
  • 48
  • 82
  • Possible duplicate of [List of tuples to dictionary](https://stackoverflow.com/questions/6522446/list-of-tuples-to-dictionary) – Anand Tripathi Jun 21 '18 at 13:05

4 Answers4

10

Just use dict.update.

>>> myD = {'key1': 123 , 'key2': 456}
>>> myL = [('fkey1',321),('fkey2',432),('fkey3',543)]
>>> 
>>> myD.update(myL)
>>> 
>>> myD
{'key2': 456, 'key1': 123, 'fkey1': 321, 'fkey2': 432, 'fkey3': 543}
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
timgeb
  • 76,762
  • 20
  • 123
  • 145
4

use simple for loop statment

myD = {'key1': 123 , 'key2': 456}

myL = [('fkey1',321),('fkey2',432),('fkey3',543)]

for k, v in myL:
    myD[k] = v

print(myD)

or use update

myD.update(myL)                                                                                                                                                                                              

print(myD)

Output

{'key1': 123, 'key2': 456, 'fkey1': 321, 'fkey2': 432, 'fkey3': 543}
Druta Ruslan
  • 7,171
  • 2
  • 28
  • 38
4

Use dict.update

Ex:

myD = {'key1': 123 , 'key2': 456}
myL = [('fkey1',321),('fkey2',432),('fkey3',543)]
myD.update(myL)
print(myD)

Output:

{'key2': 456, 'key1': 123, 'fkey1': 321, 'fkey2': 432, 'fkey3': 543}
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

Dictionary unpacking:

>>> >>> myD = {'key1': 123 , 'key2': 456}
>>> myL = [('fkey1',321),('fkey2',432),('fkey3',543)]
>>> {**myD, **dict(myL)}
{'key1': 123, 'key2': 456, 'fkey1': 321, 'fkey2': 432, 'fkey3': 543}
RoadRunner
  • 25,803
  • 6
  • 42
  • 75