87

Given the following dictionary:

dct = {'a':3, 'b':3,'c':5,'d':3}

How can I apply these values to a list such as:

lst = ['c', 'd', 'a', 'b', 'd']

in order to get something like:

lstval = [5, 3, 3, 3, 3]
wim
  • 338,267
  • 99
  • 616
  • 750
ulrich
  • 3,547
  • 5
  • 35
  • 49
  • 10
    What happens if the value in the list is not present in the dictionary? – Anand S Kumar Oct 12 '15 at 10:12
  • 2
    Possible duplicate of [Python dictionary: Get list of values for list of keys](http://stackoverflow.com/questions/18453566/python-dictionary-get-list-of-values-for-list-of-keys) – user Oct 26 '15 at 07:39
  • 3
    In case you are wondering about the reason behind all these unexplained downvotes, your question was linked from meta: http://meta.stackoverflow.com/questions/308731/failing-first-post-review-trivial-question-with-no-research-had-15 – user000001 Oct 26 '15 at 13:10

9 Answers9

115

Using a list comprehension:

>>> [dct[k] for k in lst]
[5, 3, 3, 3, 3]

Using map:

>>> [*map(dct.get, lst)]
[5, 3, 3, 3, 3]
wim
  • 338,267
  • 99
  • 616
  • 750
  • 2
    This seems like the best one using map, you don't need lambda for this. – Anand S Kumar Oct 12 '15 at 10:16
  • 33
    It's worth noting that in python 3.x you need to type `list(map(dct.get, lst))` to get actual results back, otherwise you'll get an iterator object. – Leb Oct 12 '15 at 11:52
18

You can use a list comprehension for this:

lstval = [ dct.get(k, your_fav_default) for k in lst ]

I personally propose using list comprehensions over built-in map because it looks familiar to all Python programmers, is easier to parse and extend in case a custom default value is required.

Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71
  • [Why use list-comp over `map`?](https://docs.python.org/3.0/whatsnew/3.0.html#views-and-iterators-instead-of-lists) *Particularly tricky is map() invoked for the side effects of the function; the correct transformation is to use a regular for loop (since creating a list would just be wasteful).* :) – Bhargav Rao Oct 25 '15 at 19:44
  • @Oleg: That's why I have `dct.get(k, your_fav_default)` in place. If values are missing it should give back the `your_fav_default` – Sanjay T. Sharma Oct 27 '15 at 13:15
15

You can iterate keys from your list using map function:

lstval = list(map(dct.get, lst))

Or if you prefer list comprehension:

lstval = [dct[key] for key in lst]
Eugene Soldatov
  • 9,755
  • 2
  • 35
  • 43
8
lstval = [d[x] for x in lst]

Don't name your dictionary dict. dict is the name of the type.

khelwood
  • 55,782
  • 14
  • 81
  • 108
4

Do not use a dict as variable name, as it was built in.

>>> d = {'a':3, 'b':3,'c':5,'d':3}
>>> lst = ['c', 'd', 'a', 'b', 'd']
>>> map(lambda x:d.get(x, None), lst)
[5, 3, 3, 3, 3]
luoluo
  • 5,353
  • 3
  • 30
  • 41
4

I would use a list comprehension:

listval = [dict.get(key, 0) for key in lst]

The .get(key, 0) part is used to return a default value (in this case 0) if no element with this key exists in dict.

TobiMarg
  • 3,667
  • 1
  • 20
  • 25
  • @Oleg The code is iterating over elements of `lst` not keys in the dictionary. So there could be something in `lst` and no corresponding key in the dict (even when this wouldn't make much sense) and we need to handle that case. – TobiMarg Oct 28 '15 at 17:46
  • Use listval = [dic_rev.get(key, key) for key in y] to return original values that do not appear as keys in the dictionary you want to use – Alvaro Romero Diaz Sep 19 '19 at 13:29
2

In documentation of Python 3:

So, zip(*d.items()) give your result.

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

print(d.items())        # [('a', 1), ('c', 3), ('b', 2), ('d', 4)] in Python 2
                        # dict_items([('a', 1), ('c', 3), ('b', 2), ('d', 4)]) in Python 3

print(zip(*d.items()))  # [('a', 1), ('c', 3), ('b', 2), ('d', 4)] in Python 2
                        # <zip object at 0x7f1f8713ed40> in Python 3

k, v = zip(*d.items())
print(k)                # ('a', 'c', 'b', 'd')
print(v)                # (1, 3, 2, 4)
Olivier Pirson
  • 737
  • 1
  • 5
  • 24
1

Mapping dictionary values to a nested list

The question has already been answered by many. However, no one has mentioned a solution in case the list is nested.

By changing the list in the original question to a list of lists

dct = {'a': 3, 'b': 3, 'c': 5, 'd': 3}    

lst = [['c', 'd'], ['a'], ['b', 'd']]

The mapping can be done by a nested list comprehension

lstval = [[dct[e] for e in lst[idx]] for idx in range(len(lst))]

# lstval = [[5, 3], [3], [3, 3]]
petezurich
  • 9,280
  • 9
  • 43
  • 57
Tim Skov Jacobsen
  • 3,583
  • 4
  • 26
  • 23
1

Anand S Kumar rightfully pointed out that you run into problems when a value in your list is not available in the dictionary.

One more robust solution is to add an if/else condition to your list comprehension. By that you make sure the code doesn't break.

By that you only change the values in the list where you have a corresponding key in the dictionary and otherwise keep the original value.

m = {'a':3, 'b':3, 'c':5, 'd':3}
l = ['c', 'd', 'a', 'b', 'd', 'other_value']
l_updated = [m[x] if x in m else x for x in l]

[OUT]

[5, 3, 3, 3, 3, 'other_value']
petezurich
  • 9,280
  • 9
  • 43
  • 57