Using python 3.6
Say I had this dictionary
and list
structure of keys
:
dictionary = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
keys = [['a','b'], ['c','d','e']]
Whats the best way to get this?
values = [[1, 2], [3, 4, 5]]
Thanks!
Here's an alternative approach with a 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]
Output:
[[1, 2], [3, 4, 5]]
One huge plus point is it's a lot more robust with handling non-existent keys (thanks, @Ev.Kounis!).
Alternative ft. Ev Kounis involving returning a default value on no-key:
items = [[dictionary.get(x, 0) for x in sub] for sub in keys]
You can try this:
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]
Output:
[[1, 2], [3, 4, 5]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With