Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append a list of tuples into a existing dictionary

Tags:

python

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?

like image 290
Malintha Avatar asked Dec 02 '22 10:12

Malintha


2 Answers

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}
like image 55
timgeb Avatar answered Dec 04 '22 00:12

timgeb


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}
like image 20
Druta Ruslan Avatar answered Dec 03 '22 23:12

Druta Ruslan