Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, copying a rank 2 list structure with different values

Tags:

python

list

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!

like image 677
James Schinner Avatar asked Jan 31 '23 02:01

James Schinner


2 Answers

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]
like image 176
cs95 Avatar answered Feb 02 '23 10:02

cs95


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]]
like image 26
Ajax1234 Avatar answered Feb 02 '23 10:02

Ajax1234