![](/img/trans.png)
[英]How to add values from one dictionary to another based on matching keys?
[英]How to remove dictionary's keys and values based on another dictionary?
我希望根據另一個JSON字典的鍵和值刪除一個JSON字典中的鍵和值。 從某種意義上說,我正在尋找一種“減法”。 假設我有JSON字典a
和b
:
a = {
"my_app":
{
"environment_variables":
{
"SOME_ENV_VAR":
[
"/tmp",
"tmp2"
]
},
"variables":
{ "my_var": "1",
"my_other_var": "2"
}
}
}
b = {
"my_app":
{
"environment_variables":
{
"SOME_ENV_VAR":
[
"/tmp"
]
},
"variables":
{ "my_var": "1" }
}
}
想象一下,你可以做a
- b
= c
其中c
看起來是這樣的:
c = {
"my_app":
{
"environment_variables":
{
"SOME_ENV_VAR":
[
"/tmp2"
]
},
"variables":
{ "my_other_var": "2" }
}
}
如何才能做到這一點?
您可以使用字典中for key in dictionary:
遍歷for key in dictionary:
並且可以使用del dictionary[key]
刪除關鍵字,我想這就是您所需要的。 請參閱字典文檔: https : //docs.python.org/2/tutorial/datastructures.html#dictionaries
以下內容滿足您的需求:
def subtract(a, b):
result = {}
for key, value in a.items():
if key not in b or b[key] != value:
if not isinstance(value, dict):
if isinstance(value, list):
result[key] = [item for item in value if item not in b[key]]
else:
result[key] = value
continue
inner_dict = subtract(value, b[key])
if len(inner_dict) > 0:
result[key] = inner_dict
return result
它檢查key
和value
是否都存在。 它可以del
項目,但我認為返回帶有所需數據的新字典而不是修改原始字典要好得多。
c = subtract(a, b)
UPDATE
我剛剛更新了問題中提供的數據的最新版本。 現在,它也“減去”列表值。
更新2
工作示例: ipython筆記本
您可以這樣做:
a
- > c
; b
內的每個key, value
對; top keys
是否具有相同的inner keys and values
,並從c
刪除它們; empty values
keys
。 如果您的情況有所不同,則應修改代碼(無dict(dict)
等)。
print(A)
print(B)
C = A.copy()
# INFO: Suppose your max depth is as follows: "A = dict(key:dict(), ...)"
for k0, v0 in B.items():
# Look for similiar outer keys (check if 'vars' or 'env_vars' in A)
if k0 in C:
# Look for similiar inner (keys, values)
for k1, v1 in v0.items():
# If we have e.g. 'my_var' in B and in C and values are the same
if k1 in C[k0] and v1 == C[k0][k1]:
del C[k0][k1]
# Remove empty 'vars', 'env_vars'
if not C[k0]:
del C[k0]
print(C)
{'environment_variables': {'SOME_ENV_VAR': ['/tmp']},
'variables': {'my_var': '2', 'someones_var': '1'}}
{'environment_variables': {'SOME_ENV_VAR': ['/tmp']},
'variables': {'my_var': '2'}}
{'variables': {'someones_var': '1'}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.