Eli Spencer
Eli Spencer

Reputation: 31

find Key for value in python when key associated with multiple values

For a dictionary of the type

{'key1': ['v1','v2','v3', ...],
 'key2': ['v2','v4', ...],
  ... }

How do I

  1. Find any key associated with a value v
  2. Print that k:[value set] pair to a new dictionary

Upvotes: 3

Views: 6893

Answers (3)

martineau
martineau

Reputation: 123473

Actually it's faster and simpler to answer the second question (put any matching pairs found into a new_dictionary) first, then just extract the list of keys from it to answer the first question.

old_dict = {'key1': ['v1','v2','v3','v56','v99'],
            'key2': ['v2','v4','v42','v17'],
            'key3': ['v0','v3','v4','v17','v49'],
            'key4': ['v23','v14','v42'],
           }

v = 'v42'
new_dict = dict(pair for pair in old_dict.iteritems() if v in pair[1])
print 'new_dict:', new_dict
# new_dict: {'key2': ['v2', 'v4', 'v42', 'v17'], 'key4': ['v23', 'v14', 'v42']}

keys_with_value = new_dict.keys()
print 'keys_with_value:', keys_with_value
# keys_with_value: ['key2', 'key4']

Upvotes: 1

BlackShift
BlackShift

Reputation: 2406

In python 3 it's even nicer:

>>> old_dict = {'key1':['v1','v2','v3'], 'key2':['v2','v4']}
>>> keys_with_value = [k for k, v in old_dict.items() if "v2" in v]
>>> new_dict = {k: v for k, v in old_dict.items() if "v2" in v}

Same result as Daniel DiPaolo has. Note the .items() instead of .iteritems().

Upvotes: 0

Daniel DiPaolo
Daniel DiPaolo

Reputation: 56390

# answer to 1st question
keys_with_value = [k for k, v in old_dict.iteritems() if "whatever_value" in v]

# answer to 2nd question
new_dict = {}   
for k in keys_with_value:
   new_dict[k] = old_dict[k]

Example:

>>> old_dict = {'key1':['v1','v2','v3'], 'key2':['v2','v4']}
>>> keys_with_value = [k for k, v in old_dict.iteritems() if "v2" in v]
>>> new_dict = {}
>>> for k in keys_with_value:
       new_dict[k] = old_dict[k]

>>> new_dict
{'key2': ['v2', 'v4'], 'key1': ['v1', 'v2', 'v3']}

>>> new_dict = {}
>>> keys_with_other_value = [k for k, v in old_dict.iteritems() if "v1" in v]
>>> for k in keys_with_other_value:
       new_dict[k] = old_dict[k]

>>> new_dict
{'key1': ['v1', 'v2', 'v3']}

Upvotes: 1

Related Questions