在词典列表中搜索键,值

时间:2016-04-03 16:56:13

标签: python

回答问题:

经过一些帮助,我意识到它正在破碎,因为它正在扫描电子邮件,而一封电子邮件会有我想要的东西,其余的没有,因此导致它破裂。

添加Try / Except解决了这个问题。只是为了历史的缘故,任何其他人都在寻找类似的问题,这是有效的代码。

try:
  if (item for item in list_of_dict if item['name'] == "From" and item['value'] == 'NAME1 <name@some_email.com>').next():
    print('has it')
  else:
    pass
except StopIteration:
  print("Not found")

通过这种方式,它可以扫描每封电子邮件并在出现故障时进行错误处理,但如果它发现它能够打印出来,那么我找到了我想要的东西。

原始问题:

代码:

if (item for item in list_of_dict if item['name'] == "From" and item['value'] == 'NAME1 <name1@some_email.com>').next()

我收到StopIteration错误:

Traceback (most recent call last):
  File "quickstart1.py", line 232, in <module>
    main()
  File "quickstart1.py", line 194, in main
    if (item for item in list_of_dict if item['name'] == "From" and item['value'] == 'NAME1 <name1@some_email.com>').next():
StopIteration

这是我的代码:

if (item for item in list_of_dict if item['name'] == "From" and item['value'] == 'NAME1 <name1@some_email.com>').next():
      print('has it')
else:
  print('doesnt have it')

当我检查我是否错误地放入迭代器时,我查找了项目[&#39; value&#39;]:

print((item for item in list_of_dict if item['name'] == "From").next())

返回:

{u'name': u'From', u'value': u'NAME1 <name1@some_email.com>'}
{u'name': u'From', u'value': u'NAME2 <name2@some_email.com>'}

3 个答案:

答案 0 :(得分:1)

只需通过and添加其他条件:

next(item for item in dicts if item["name"] == "Tom" and item["age"] == 10)

请注意,next()如果没有匹配则会引发StopIteration例外,您可以通过try/except处理该问题:

try:
    value = next(item for item in dicts if item["name"] == "Tom" and item["age"] == 10)
    print(value)
except StopIteration:
    print("Not found")

或者,提供默认值

next((item for item in dicts if item["name"] == "Tom" and item["age"] == 10), "Default value")

答案 1 :(得分:0)

如果要检查是否包含任何字典,可以使用默认参数next

iter = (item for item in list_of_dict if item['name'] == "From" and item['value'] == 'name <email>')

if next(iter, None) is not None: # using None as default
    print('has it')
else:
    print('doesnt have it')

但这也会排除None个常规项目,因此您还可以使用tryexcept

try:
    item = next(iter)
except StopIteration:
    print('doesnt have it')    
else: 
    print('has it') # else is evaluated only if "try" didn't raise the exception.

但请注意,生成器只能使用一次,因此如果要再次使用它,请重新创建生成器:

iter = ...
print(list(iter))
next(iter) # <-- fails because generator is exhausted in print

iter = ...
print(list(iter))
iter = ...
next(iter) # <-- works

答案 2 :(得分:0)

dicts = [
     { "name": "Tom", "age": 10 },
     { "name": "Pam", "age": 7 },
      { "name": "Dick", "age": 12 }
   ]

super_dict = {}    # will be {'Dick': 12, 'Pam': 7, 'Tom': 10}
for d in dicts:
    super_dict[d["name"]]=d['age']

if super_dict["Tom"]==10:
    print 'hey, Tom is really 10'