Prabhanjan
Prabhanjan

Reputation: 185

Match a value to key value and get key

let's say I need do this: I need to match the values in list 'check_keys' against the key-values in dictionary 'parm' and store the matched keys in the same order into a new list 'insert'

parm = {'f': 'w', 'l': 'b', 'b': 'y', 'u': 'o', 't': 'r', 'r': 'g'}
check_keys = ['r','b','o','g','w','y']
insert = ['t','l','u','r','f','b']

Upvotes: 0

Views: 2424

Answers (5)

vash_the_stampede
vash_the_stampede

Reputation: 4606

You could use list comprehension to solve this

insert = [k for i in check_keys for k in parm if parm[k] == i]
# ['t', 'l', 'u', 'r', 'f', 'b']

Upvotes: 0

ShaharA
ShaharA

Reputation: 903

One possible way is the reverse the dictionary, which can be done in linear time (relative to the size of your parm dict) on average.

Once the dictionary is reversed your searched values become keys And are now easily accessible is O(1) per key in your check_keys list.

rev_parm = dict((v, k) for k, v in parm.items())
insert = [rev_parm[k] for k in check_keys]

Upvotes: 1

everybody0523
everybody0523

Reputation: 152

This is not a great use of a Hash Table/Dictionary. A Hash Table gives you fast access to the values, given the keys of the dictionary. Here, you are trying to access the keys of the dictionary, given the values (ie. the other way around).

This is bad because:

  • It's slow. You will need to iterate over the entire dictionary to find your values.
  • The result is non-deterministic, as dictionaries are unordered. If your inputs were instead parm = {'a': 'r', 'b': 'r'}, check_keys = [r], it is uncertain whether you would get [a], or [b].

With all that said and done, this should solve your problem:

parm = {'f': 'w', 'l': 'b', 'b': 'y', 'u': 'o', 't': 'r', 'r': 'g'}
check_keys = ['r','b','o','g','w','y']
insert = ['t','l','u','r','f','b']

insert = []
for v in check_keys:
    for k in parm:
        if parm[k] == v:
            insert.append(k)

print insert

Assuming, of course, that this is part of a larger program, I would suggest that you do NOT use the above approach, but instead re-evaluate your entire approach.

Upvotes: 0

wasle
wasle

Reputation: 14

It took some time but i think i figured out what you want to do.

If i am correct you wan't to reverse look up the dictionary from value to key. The easiest way would be to cerate the reverse dictionary.

rparm = dict( (value,key) for key,value in parm.items())

Then match the data e.g.

insert = [rparm[key] for key in check_keys]

Sorry for using all this list and generator comprehensions. If our are not familiar with them I can add the classic for loop version.

Upvotes: 0

Michael Marx
Michael Marx

Reputation: 159

Maybe something like this?

insert = []
for k, v in parm.items():
    if k in check_keys:
        insert.append(k)

Or this shorter version:

insert = [k for k, v in parm.items() if k in check_keys]

Upvotes: 0

Related Questions