简体   繁体   中英

How to map identical items in two dictionaries and produce a list of values of their corresponding keys

My goal is to map the small dictionary to the large one and return a list of values in the large dictionary that bears corresponding keys to the small dictionary.

x={'red':0.25, 'yellow':0.05, 'pink':0.35, 'brown':0.22, 'blue':0.13}
y={'red':2, 'blue':3, 'yellow':1}

My code keeps giving me a list of the full values of large dictionary.

for b in x.keys():
    if b in y.keys():
        k=y.values()
print k

output: [0.35, 0.22, 0.13, 0.05, 0.25]

Desired output:
[0.25,0.13,0.05]

Any suggestions? Thanks.

Something like this? I assume that the order does not matter since these are dictionaries. Also, assuming that since you seem to be iterating over x.keys() , then, there may be some values in y that are not present in x and you don't want them mapped.

>>> x={'red':0.25, 'yellow':0.05, 'pink':0.35, 'brown':0.22, 'blue':0.13}
>>> y={'red':2, 'blue':3, 'yellow':1}
>>> [val for elem, val in x.items() if elem in y]
[0.13, 0.05, 0.25]

If there are no values in y that are not in x , then you could simply iterate over the y dictionary.

>>> [x[key] for key in y]
[0.13, 0.05, 0.25]

PS - The problem in your code is that everytime you find a match, you assign the whole list of y.values() to k , hence ending up with a complete list of values. You could modify your code to look something like this

>>> k = []
>>> for b in x.keys():
    if b in y.keys():
        k.append(x[b])


>>> k
[0.13, 0.05, 0.25]

Although, iterating over the dictionary gives a similar result, like follows

>>> for b in x:
    if b in y:
        k.append(x[b])


>>> k
[0.13, 0.05, 0.25]
k = [x[key] for key in y.keys()]

The issue with your code is, you are assigning y.values() to k . So your k is nothing but the list of values of dict y . You can modify your code like this to make it work:

k = []
for b in x.keys():
    if b in y.keys():
        k.append(x[b])
print k

You can also use List comprehension:

>>> x={'red':0.25, 'yellow':0.05, 'pink':0.35, 'brown':0.22, 'blue':0.13}
>>> y={'red':2, 'blue':3, 'yellow':1}

>>> [x[key] for key in y]
[0.13, 0.05, 0.25]

I would think about this as the intersection of two sets, then pass the subset to map all of the corresponding values. This way it would be much easier to understand than list comprehension.

>>> map(x.get, set(x) & set(y))
>>> [0.13, 0.05, 0.25]

Of course you can do the same with list comprehension:

>>> [x.get(i) for i in set(x) & set(y)]
>>> [0.13, 0.05, 0.25]

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