Python copying a rank 2 list structure with different values

Using python 3.6

Let's say I had this structure dictionaryand list keys:

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

keys = [['a','b'], ['c','d','e']]

What is the best way to get this?

values = [[1, 2], [3, 4, 5]]

Thank!

+4
source share
2 answers

Here's an alternative approach with map:

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

items = [list(map(dictionary.get, k)) for k in keys]

Conclusion:

[[1, 2], [3, 4, 5]]

One huge plus is a much more reliable way to handle non-existent keys (thanks, @ Ev.Kounis!).


Alternative ft. Ev Kounis, including returning the default value to no-key:

items = [[dictionary.get(x, 0) for x in sub] for sub in keys]
+4
source

You can try the following:

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

keys = [['a','b'], ['c','d','e']]

new = [[dictionary[b] for b in i] for i in keys]

Conclusion:

[[1, 2], [3, 4, 5]]
+4
source

Source: https://habr.com/ru/post/1680726/


All Articles