![](/img/trans.png)
[英]Trying to conditionally append tuples from a list of tuples to sublists of tuples in a dictionary
[英]Append a list of tuples into a existing dictionary
我有一个现有的字典,我想在这个字典中添加一个元组列表。
现有字典结构:
myD = {'key1': 123 , 'key2': 456}
元组结构列表:
myL = [('fkey1',321),('fkey2',432),('fkey3',543)]
添加元组列表后的预期字典
myD = {'key1': 123 ,'key2': 456 ,'fkey': 321 ,'fkey2': 432 ,'fkey3': 543}
我怎么能在python中实现这个?
只需使用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}
使用简单的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)
或使用update
myD.update(myL)
print(myD)
产量
{'key1': 123, 'key2': 456, 'fkey1': 321, 'fkey2': 432, 'fkey3': 543}
使用dict.update
例如:
myD = {'key1': 123 , 'key2': 456}
myL = [('fkey1',321),('fkey2',432),('fkey3',543)]
myD.update(myL)
print(myD)
输出:
{'key2': 456, 'key1': 123, 'fkey1': 321, 'fkey2': 432, 'fkey3': 543}
字典拆包:
>>> >>> 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.