2010-12-21 44 views
2

當密鑰關聯對於這種類型的詞典找到在python價值主要有多個值

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

我如何

  1. 找到與值v
  2. 打印相關的密鑰k:[數值設置]配對到一本新字典
+0

你的意思是用新的鍵值對填充一個新字典?不打印。 – marcog 2010-12-21 21:58:31

回答

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] 

實施例:

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

在Python 3,它甚至更好:作爲丹尼爾戴保羅具有

>>> 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} 

相同的結果。注意.items()而不是.iteritems()。

1

實際上,回答第二個問題(將找到的任何匹配對放入new_dictionary中)然後從中提取鍵列表來回答第一個問題會更快更簡單。

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