访问字典值时,如何归因于NaN'如果某个密钥没有值?

时间:2016-10-10 00:04:32

标签: python python-3.x dictionary nan key-value

我正在遍历字典并访问字典值以附加到列表中。

以一个字典为例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语句?

1 个答案:

答案 0 :(得分:2)

您可以检查不是""的值,只需执行以下操作:

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

因此,如果second中存在密钥new_dict且字符串为空,则NaN将附加到second_list

如果您希望使用上面的逻辑从字典中创建值列表,您可以执行以下操作,两者都相同,第一个是扩展,第二个是缩短的理解:

方法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()]