![](/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.