How to combine a dictionary + list to form one sorted list

Ok i have a dictionary like this

z = {'J': 50, 'Q': 30, 'F': 10) 

And a list that looks like

 l = [('J', 20), ('Q', 10), ('F', 2)] 

How to combine them into a dictionary or list while keeping the sorting of my source list? I want something like

 l = [('J', 20, 50), ('Q', 10, 30), ('F', 2, 10)] 

Thanks for the help!

+4
source share
3 answers
 z = {'J': 50, 'Q': 30, 'F': 10} l = [('J', 20), ('Q', 10), ('F', 2)] print [(a, b, z[a]) for a, b in l] 

gives:

 [('J', 20, 50), ('Q', 10, 30), ('F', 2, 10)] 

Better not call your list l . From PEP 8 :

Names to Avoid

Never use the characters 'l' (lowercase el), 'O' (uppercase letter oh) or "I" (eye in uppercase letters) as a single character variable names.

In some fonts, these characters are indistinguishable from the numbers one and zero. When tempted to use 'l', use 'l' instead.

+6
source

List of tuples you can do:

 [item + (z[item[0]],) for item in l] 

Note that z[item[0]] assumes that the key item[0] always exists in z .

For the dict parameter try

 dict((item[0], (item[1], z[item[0]])) for item in l) 
0
source

Improving the response to jena so that some elements from the list are not present in the dict:

 >>> l = [('J', 20), ('Q', 10), ('F', 2), ('A', 5)] >>> [x + (z.get(x[0]),) for x in l] [('J', 20, 50), ('Q', 10, 30), ('F', 2, 10), ('A', 5, None)] 
0
source

All Articles