[英]find specific value in python dictionary
I am having trouble. 我有麻烦了。 This is my code, I would like to check if a specific value exist in the dictionary. 这是我的代码,我想检查字典中是否存在特定值。 This is my code. 这是我的代码。 I think the logic is right but the syntax is not correct. 我认为逻辑是正确的,但语法不正确。 Please help me. 请帮我。 Thank you. 谢谢。
a = [
{'amount':200, 'currency':'php'},
{'amount':100, 'currency':'usd'}
]
result1 = 200 in a
result2 = 'php' in a
result = result1 and result2
print result
I am expecting to have a result of 'True' 我期望得到的结果是“ True”
The line 线
result1 = 200 in a
looks for a list element with the value of 200
. 查找值为200
的列表元素。 But your list elements are dictionaries. 但是您的列表元素是字典。 So your expectations are impossible to achieve as stated. 因此,您无法实现上述预期。
So, assuming your goal is to check a particular value is contained in any of the elements (ie dictionaries) of list a
, you should write 因此,假设您的目标是检查列表a
任何元素(即字典)中包含的特定值,则应编写
result1 = any(200 in el.values() for el in a)
result2 = any('php' in el.values() for el in a)
result = result1 and result2
print result
which produces 产生
True
Use iteritems to iterate thru dictionary gettings its keys and values 使用迭代项遍历字典获取其键和值
a = [
{'amount':200, 'currency':'php'},
{'amount':100, 'currency':'usd'}
]
for lst in a:
for k,v in lst.iteritems():
if 200 == v:
res1 = 'True'
if 'php' == v:
res2 = 'True'
print res1 and res
You can do something like 你可以做类似的事情
a = [
{'amount':200, 'currency':'php'},
{'amount':100, 'currency':'usd'}
]
for i in a:
if 200 in i.values():
result1=True
if "php" in i.values():
result2=True
result = result1 and result2
print result
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.