[英]How to append key value pair to an existing list of dict from another list of dict based on matching Key in Python
[英]How to replace a Value in a Dict from another Dict but based on a key value in the first Dict
可以說我有兩個這樣的字典:
dict1 = {'project' : 'Administration', 'cost_center' : 'N/A'}
{'project' : 'Non-Work Time', 'cost_center' : 'N/A'}
dict2 = {'project':'Administration', 'cost_center': 'F99'}
{'project':'Non-Work Time', 'cost_center': 'F88'}
我需要幫助,找到一種用dict2 cost_center中的值替換“ N / A”的方法。 我認為IF語句最好是:如果找到“ N / A”,則用dict2中的值替換,如果找不到,則將其保留為“ N / A”
所需輸出示例:
dict1 = {'project' : 'Administration', 'cost_center' : 'F99'}
{'project' : 'Non-Work Time', 'cost_center' : 'F88'}
偽:
if dict1['cost_center'] == "N/A':
Replace 'cost' if 'project' == exists in dict2
else:
continue
您可以使用dict理解:
>>> dict1 = {'project' : 'Non-Work Time', 'cost' : 'N/A'}
>>> dict2 = {'Administration': 'F99' , 'Non-Work Time': 'Q99'}
>>> dict1 = {i:dict2[dict1['project']] if i=='cost' and j=='N/A' else j for i,j in dict1.items()}
>>> dict1
{'project': 'Non-Work Time', 'cost': 'Q99'}
但是請注意,您的字典中必須包含預期的鍵,否則它將引發KeyError
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.