我有一個字典,其中包含爲每個鍵存儲的多個值的列表。我要檢查,如果給定值在字典中,但是這並不工作:具有多個值的鍵 - 檢查值是否在字典中python
if 'the' in d.values():
print "value in dictionary"
爲什麼不與存儲作爲一個列表中選擇多個值工作?有沒有其他方法來測試該值是否在字典中?
我有一個字典,其中包含爲每個鍵存儲的多個值的列表。我要檢查,如果給定值在字典中,但是這並不工作:具有多個值的鍵 - 檢查值是否在字典中python
if 'the' in d.values():
print "value in dictionary"
爲什麼不與存儲作爲一個列表中選擇多個值工作?有沒有其他方法來測試該值是否在字典中?
您的值是一個列表!
for item in d.values():
if 'the' in item:
print "value in dictionary"
d.values()
通常以列表格式存儲值。因此,您需要遍歷列表內容並檢查子字符串the
是否存在。
>>> d = {'f':['the', 'foo']}
>>> for i in d.values():
if 'the' in i:
print("value in dictionary")
break
value in dictionary
它應該是非常簡單的:
>>> d = { 'a': ['spam', 'eggs'], 'b': ['foo', 'bar'] }
>>> 'eggs' in d.get('a')
True
您可以在字典迭代。 如果您的詞典看起來像如下:
my_dictionary = { 'names': ['john', 'doe', 'jane'], 'salaries': [100, 200, 300] }
然後,你可以做到以下幾點:
for key in my_dictionary:
for value in my_dictionary[key]:
print value
你自然可以搜索,而不是打印。像這樣:
for key in my_dictionary:
for value in my_dictionary[key]:
if "keyword" in value:
print "found it!"
有可能是一個更短的方法來做到這一點,但這也應該工作。
縮進需要修復。 – 2015-02-10 14:36:53
是的。我的錯。固定。 – Onedot618 2015-02-10 14:37:39
如果你只是要檢查一個值是否存在與否而無需知道它屬於項和所有,你可以用這個去:
if 'the' in str(d.values())
還是爲了一襯,您可以使用過濾功能
if filter(lambda x: 'eggs' in x, d.values()) # To just check
filter(lambda x: 'eggs' in d[x] and x, d) # To get all the keys with the value
我喜歡寫
if 0 < len([1 for k in d if 'the' in d[k]]):
# do stuff
或等價
if 0 < len([1 for _,v in d.iteritems() if 'the' in v]):
# do stuff
'if any('the'in value in d.values()):'?但是如果你需要去查找所有的值列表,你可能沒有最好的數據結構。 – jonrsharpe 2015-02-10 14:02:54