Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to map the keys of a dictionary onto the values of another?

Say you're working with these two dictionaries:

a={(1,2):1.8,(2,3):2.5,(3,4):3.9} #format -> {(x,y):value}
b={10:(1,2),20:(2,3),30:(3,4)} #format -> {id:(x,y)}

and you want to come up with a dictionary that has the following format: {id:value}. In this example, the result would be:

c={10:1.8,20:2.5,30:3.9}

I have tried the following

c={k:j for k in b.keys() and j in a.values()}

but the result is an apparently trivial

NameError: name 'j' is not defined

What's the best way of doing this? How do you "model" the correspondence?

like image 271
FaCoffee Avatar asked Feb 17 '17 14:02

FaCoffee


People also ask

How do you map keys and values in Python?

In this, we iterate the list keys and construct dictionary of required key-value pairs using dictionary comprehension. The combination of above functions can also be used to solve this problem. In this, we perform conversion to dictionary using dict() and extract dictionary values using values().

Can a key map to multiple values Python?

In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.

How do you map a dictionary value?

Write a Python program to map the values of a given list to a dictionary using a function, where the key-value pairs consist of the original value as the key and the result of the function as the value. Use map() to apply fn to each value of the list. Use zip() to pair original values to the values produced by fn.


1 Answers

Iterating over b only seems sufficient - why not just use the natural correspondence of the dict.

>>> {k: a[v] for k, v in b.items()}
{10: 1.8, 20: 2.5, 30: 3.9}

A correct syntactical attempt at your idea would be something like

>>> {k:j for k, j in zip(b.keys(),a.values())}
{10: 1.8, 20: 3.9, 30: 2.5}

However as you can see, this doesn't work anyways. This is because dicts are of course unordered, and so there is no enforced relation between the keys of one dict and the values of another.

like image 73
miradulo Avatar answered Oct 05 '22 22:10

miradulo