[英]Append a list of tuples into a existing dictionary
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? 我怎么能在python中实现这个?
Just use dict.update
. 只需使用
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
使用简单的
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
或使用
update
myD.update(myL)
print(myD)
Output 产量
{'key1': 123, 'key2': 456, 'fkey1': 321, 'fkey2': 432, 'fkey3': 543}
Use dict.update
使用
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}
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}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.