繁体   English   中英

在词典列表中搜索键,值

[英]Searching for Key, Value in a list of dictionaries

回答问题:

经过一番帮助,我意识到它正在崩溃,因为它正在扫描电子邮件,而当一封电子邮件可以满足我的需求时,其余的却没有,因此导致其崩溃。

添加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')

当我检查我是否错误地放入迭代器时,我对item ['value']进行了查找:

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

只需通过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")

如果要检查是否有任何字典,可以使用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
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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM