[英]Python 2.7 append values to dictionary
I have 2 dictionaries with identical keys. 我有2个具有相同键的字典。
d1 = {'Dog':[7,2],'Cat':[5,2]}
d2 = {'Dog':1,'Cat':4}
Is there a good way of combining them so that I can have one dictionary that looks like this? 有没有很好的方法将它们组合在一起,以便我可以拥有一个像这样的字典?
d = {'Dog':[7,2,1],'Cat':[5,2,4]}
for key, value in d2.iteritems():
if key in d1:
d1[key].append(value)
如果一个包含列表,另一个包含整数,则可以执行以下操作:
d = {key:[d2[key]] + d1[key] for key in d1}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.