Reputation: 185
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
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
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
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:
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
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
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