0

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}?

Udo Klein
  • 6,784
  • 1
  • 36
  • 61

2 Answers2

2
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}

eumiro
  • 207,213
  • 34
  • 299
  • 261
  • nice answer, [here is a method](http://stackoverflow.com/questions/1747817/python-create-a-dictionary-with-list-comprehension?answertab=votes#tab-top) using `dict()` how to use for this purpose. – Grijesh Chauhan Feb 27 '13 at 10:32
0
d = {'a':1, 'b':2, 'c':3, 'd':4}
c = ['a', 'b']
new_d = {}

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