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

匿名 (未验证) 提交于 2019-12-03 01:05:01

问题:

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

回答1:

# 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']}


回答2:

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']


回答3:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!