Mapping dictionary value to list

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]
79228 次浏览

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]

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.

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]
lstval = [d[x] for x in lst]

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

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]

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.

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)

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]]

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']