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?
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().
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.
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.
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.
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