简体   繁体   中英

How to create small dict from another dict with array of keys?

I have a simple dictionary {'a': 1, 'b': 2, 'c': 3, 'd': 4 } and list of keys: ['a', 'd'] .

What is the better way to construct dict object containing only keys from the list: {'a': 1, 'd': 4} ?

d = {'a': 1, 'b': 2, 'c': 3, 'd': 4 }
l = ['a', 'd']

new_d = {k:d[k] for k in l}

new_d is now {'a': 1, 'd': 4}

d = {'a':1, 'b':2, 'c':3, 'd':4}
c = ['a', 'b']
new_d = {}

for key in c:
    new_d[key]= d[key]

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