访问字典值时,如果某个键不存在值,如何估算 'NaN'?

When accessing dictionary values, how to impute 'NaN' if no value exists for a certain key?

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

以一本字典为例,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"))

因此,如果键 second 存在于 new_dict 中并且是一个空字符串,那么 NaN 将附加到 second_list

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

方法一

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

方法二(理解)

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