3 回答

TA貢獻1906條經(jīng)驗 獲得超3個贊
我的第一個直覺是尋找類似 Javascript “spread” 的 Python 運算符:
https://mlpipes.com/object-spread-operator-python/
這里的例子:
old_dict = {'hello': 'world', 'foo': 'bar'} new_dict = {**old_dict, 'foo': 'baz'}
對于您的代碼,您應(yīng)該嘗試以下操作:
DICTLIST[d] = {**a,**b,**c}

TA貢獻1765條經(jīng)驗 獲得超5個贊
你可以在這里使用 **kwargs
x={1:5,2:10}
y={2:10,3:20}
z={**x, **y}
如果您想進一步優(yōu)化性能,因為有多個查詢,您應(yīng)該使用“緩存+字典”,因為查找表總是比任何操作都快

TA貢獻1886條經(jīng)驗 獲得超2個贊
嘗試這個 -
def mergeDict(dict1, dict2):
dict3 = {**dict1, **dict2}
for key, value in dict3.items():
if key in dict1 and key in dict2:
dict3[key] = value + dict1[key]
return dict3
然后你可以這樣打電話 -
# Create first dictionary
dict1 = {1:5,2:10}
# Create second dictionary
dict2 = {2:10,3:20}
# Create third dictionary
dict3 = {1:-2}
dict4 = mergeDict(dict3, mergeDict(dict1, dict2))
請注意,減法邏輯的第三個字典中有“-2”。
添加回答
舉報