2016-04-03 223 views
0

答案的問題的列表:搜索鍵,值在字典

一些幫助後,我意識到,這是突破,因爲它是通過電子郵件和當一個電子郵件掃描會有什麼我一直在尋找其餘的都沒有,從而導致它破裂。

添加一個Try/Except解決了這個問題。只是爲了歷史的緣故,任何其他人都在尋找類似的問題,這是有效的代碼。

try: 
    if (item for item in list_of_dict if item['name'] == "From" and item['value'] == 'NAME1 <[email protected]_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 <[email protected]_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 <[email protected]_email.com>').next(): 
StopIteration 

這是我的代碼:

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

當我檢查,看看是否我在迭代器錯誤推杆,我做了一個查找的項目[「值」]:

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

返回:

{u'name': u'From', u'value': u'NAME1 <[email protected]_email.com>'} 
{u'name': u'From', u'value': u'NAME2 <[email protected]_email.com>'} 
+0

當發電機沒有匹配值時,會產生'StopIteration'。你必須使用'try/except'方法。 –

+0

謝謝!沒有意識到這就是stopIteration的意思! –

+0

你可以壓縮你的問題,幷包括一個[mcve] _without_編輯,並清楚地解釋你的輸入和預期輸出? – MSeifert

回答

1

只需添加另一個條件通過and

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

注意next()會拋出一個StopIterationê xception如果沒有匹配,您可以搞定通過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") 
+0

嘿@alecxe我更新了我的問題。出錯。你能看到我做錯了什麼嗎? –

+0

@MorganAllen好的,爲完整起見更新了答案。 – alecxe

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重gular項目,所以你也可以使用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 
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'