【发布时间】:2017-02-18 08:56:54
【问题描述】:
我正在遍历字典并访问字典值以附加到列表中。
以一本字典为例,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 语句?
【问题讨论】:
-
使用
.get方法;'NaN'将是一个字符串:second_list.append(new_dict.get('second', 'NaN')) -
@MosesKoledoye 你也可以使用
float('nan')。 -
请注意,从技术上讲,在这种情况下确实存在一个值,即空字符串。
标签: python python-3.x dictionary nan key-value