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?
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}
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With