0

I have a list (x) and a dictionary (d)

x=[1,3,5]
d={1:a,2:b,3:c,4:d,5:e}

As you can see a few variables match a few keys in the dictionary

But how can I print only the values whose key matches a variable in the list?

I tried a for loop but it returns only the key. Thanks for any assistance!

1
  • 1
    [d[key] for key in x]
    – Maroun
    Jan 25, 2015 at 14:05

4 Answers 4

3

Something like this?

for key in d:
    if key in x:
        print d[key]

This will loop through every key in the dictionary, and if the key appears in x then it will print the value of x.

1

try like this:

>>> x=[1,3,5]
>>> d={1:'a',2:'b',3:'c',4:'d',5:'e'}
>>> for key in d.keys():
...     if key in x:
...         print d[key]
... 
a
c
e

or you can use dict.get:

>>> for num in x:
...     print d.get(num,"not found")
... 
a
c
e

dict.get will give the value of key, if key is found in dictionary else defaultvalue

syntax : dict.get(key[, default])

1

If you are sure that all of the keys in x are in your dictionary

for key in x:
    print(d[key])

Otherwise you can check first

for key in x:
    if x in d:
        print(d[key])
0

You can use this one-liner list comprehension:

[d[key] for key in x if key in d]

This will also work if not all items in the list are keys in the dictionary.

for example:

>>> d = {1:'a', 3:'b'}
>>> x = [1, 2]
>>> [d[key] for key in x if key in d]
... ['a']

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.