简体   繁体   中英

Python 2.7 append values to dictionary

I have 2 dictionaries with identical keys.

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM