【问题标题】:When accessing dictionary values, how to impute 'NaN' if no value exists for a certain key?访问字典值时,如果某个键不存在值,如何估算“NaN”?
【发布时间】: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


【解决方案1】:

您可以检查不是"" 的值,然后简单地执行以下操作:

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

因此,如果 new_dict 中存在键 second 并且是一个空字符串,那么 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')

方法2(理解)

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

【讨论】:

  • 看起来缺失值是一个空字符串""。在这种情况下,请将new_dict.get("second", "NaN") 替换为new_dict["second"] if new_dict["second"] != "" else "NaN"。列表理解可能更简洁。
  • @SethDifley 感谢您引起我的注意,我不知何故错过了。更新我的答案。
  • 用户@MosesKoledoye 提到使用.get()。这似乎是最短的答案---它如何支持上述答案?
  • @ShanZhengYang 如果您检查我的答案的编辑,我的原始答案实际上使用了get。但人们意识到您的用例需要检查密钥是否存在但密钥没有价值。使用get('second', 'NaN') 时,仅当字典中不存在key 时才会返回NaN,这不是您想要的。在获取时阅读doc。根据您在问题中的解释,您会发现它与您的用例不匹配。
  • @idjaw 你说得对——我认为提供的解决方案确实显示了我的要求。解决方案的顶部有效,底部提供详细信息——不要删除它。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 2018-09-12
相关资源
最近更新 更多