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

4
  • 1
    And what's your way of doing it? Commented Feb 27, 2013 at 10:18
  • This was already answered here: stackoverflow.com/questions/11157704/… Commented Feb 27, 2013 at 10:20
  • I'm new to python, simple "for" loop, but it looks awful: d={'a': 1, 'b': 2, 'c': 3, 'd': 4 } l=['a','d'] r={} for key in l: r[key]=d[key] Commented Feb 27, 2013 at 10:22
  • also new to the stackoverflow, sorry Commented Feb 27, 2013 at 10:27

2 Answers 2

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}

Sign up to request clarification or add additional context in comments.

1 Comment

nice answer, here is a method using dict() how to use for this purpose.
0
d = {'a':1, 'b':2, 'c':3, 'd':4}
c = ['a', 'b']
new_d = {}

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.