简体   繁体   中英

Python: mapping a list of lists onto a dictionary

If I have a list like this

l=[[(1, 2), (1, 3)], [(1, 2), (2, 3)], [(1, 3), (2, 3)]]

and a dictionary like this

d={(1, 2): 3.61, (1, 3): 5.0, (2, 3): 6.0}

and I want to produce a list of lists that contains the values in d associated with the keys that appear in l , like this

newlist=[[3.61,5.0],[3.61,6.0],[5.0,6.0]]

How could I do it?

My attempt is

newlist=[v for k, v in d.items() if l[[i]]==k for i in l]

but this returns

TypeError: list indices must be integers, not list

Your attempt does not work because first of all the result should be a list of lists : your list comprehension will (if it would work) construct a list of values.

Furthermore it would loop only once over the dictionary (since that is the left for loop).

You can do this less error-prone and more efficient with:

newlist = [[d[x] for x in li] for li in l]

This will work given all tuples are keys in the dictionary d . If that is not the case, you can use .get(..) and specify a default value (for instance None ):

newlist = [[d.get(x,None) for x in li] for li in l]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM