2016-10-10 31 views
0

我正在遍歷字典並訪問字典值以追加到列表。訪問字典值時,如果某個鍵值不存在,如何計算'NaN'?

考慮一個詞典爲例,example_dict

example_dict = {"first":241, "second": 5234, "third": "Stevenson", "fourth":3.141592...} 
first_list = [] 
second_list = [] 
third_list = [] 
fourth_list = [] 
... 
first_list.append(example_dict["first"]) # append the value for key "first" 
second_list.append(example_dict["second"]) # append the value for key "second" 
third_list.append(example_dict["third"])  # append the value for key "third" 
fourth_list.append(example_dict["fourth"]) # append the value for key "fourth" 

我通過數百個字典的循環。有些鍵可能沒有值。在這種情況下,我想將一個NaN追加到列表中---在運行腳本之後,每個列表應該具有相同數量的元素。

如果new_dict = {"first":897, "second": '', "third": "Duchamps", ...},那麼second_list.append(new_dict["second"])將附加NaN

如何在檢查中寫入這種情況?一個if語句?

second_list.append(new_dict["second"] if new_dict["second"] != "" else "NaN")) 

所以,如果存在new_dict關鍵second,是一個空字符串,然後NaN將被追加到second_list

+0

使用'.get'方法; ''NaN''會是一個字符串:'second_list.append(new_dict.get('second','NaN'))' –

+1

@MosesKoledoye你也可以使用'float('nan')'。 –

+1

請注意,在技術上,這種情況下存在值* does *,即空字符串。 – MisterMiyagi

回答

2

您可以爲不"",只是這樣做值進行檢查。

如果你正在尋找創建從字典應用上述邏輯值的列表,則可以執行以下操作,兩者是相同的,第一被擴展,且所述第二是縮短的理解:

方法1

new_dict = {"first":897, "second": '', "third": "Duchamps"} 
new_list = [] 
for _, v in new_dict.items(): 
    if v != "": 
     new_list.append(v) 
    else: 
     new_list.append('NaN') 

方法2(理解)

new_dict = {"first":897, "second": '', "third": "Duchamps"} 
new_list = [v if v != "" else 'NaN' for _, v in new_dict.items()] 
+0

看起來像缺少的值是一個空字符串'「」'。在這種情況下,如果new_dict [「second」]!=「」else「NaN」'替換'new_dict.get(「second」,「NaN」)''new_dict [「second」]。列表理解可能更清晰。 –

+0

@SethDifley感謝您提醒我注意,我不知何故錯失了這一點。更新我的答案。 – idjaw

+0

用戶@MosesKoledoye使用'.get()'提到。這似乎是最短的答案---它如何支持上述答案? – ShanZhengYang