我有以下词典:
dict1=[{'code':'fgx23','number':23},{'code':'dx22a','number':2},{'code':'dsw23','number':10}]
dict2=[{'code':'dx22a','number':9},{'code':'dsw23','number':1},{'code':'fgx23','number':20}]
问题是:如何添加具有相同代码的数字
例如,在" dict1"代码" dx22a"有2号和" dict2"代码" dx22a"是9号,结果是11。
帮助和谢谢
答案 0 :(得分:1)
dict1=[{'code':'fgx23','number':23},{'code':'dx22a','number':2},{'code':'dsw23','number':10}]
dict2=[{'code':'dx22a','number':9},{'code':'dsw23','number':1},{'code':'fgx23','number':20}]
consolidated = {i['code']:i['number'] for i in dict1}
for i in dict2:
if i['code'] in consolidated:
consolidated[i['code']] += i['number']
else:
consolidated[i['code']] = i['number']
print(consolidated)
答案 1 :(得分:1)
dict1=[{'code':'fgx23','number':23},{'code':'dx22a','number':2},{'code':'dsw23','number':10}]
dict2=[{'code':'dx22a','number':9},{'code':'dsw23','number':1},{'code':'fgx23','number':20}]
dict3 = []
for key, value in [(i['code'], i['number']) for i in dict1]:
for value2 in ([q['number'] for q in dict2 if q['code'] == key]):
dict3.append({'code': key,'number': value + value2})
print (dict3)
这假设您只希望dict3具有出现在dict1和dict2中的键。此外,您的预期输出格式与dict1和dict2(字典列表)相同。此外,dict1和dict2中只有一个代码