Python dictionary.get()默认返回不起作用

时间:2016-07-30 05:47:36

标签: python

我尝试从字符串到字符串列表创建字典。所以我想我会使用dict.get()的默认值关键字参数:

read_failures = {}
for filename in files:
    try:
        // open file
    except Exception as e:
        error = type(e).__name__
        read_failures[error] = read_failures.get(error, []).append(filename)

所以最后我希望read_failures看起来像:

{'UnicodeDecodeError':['234.txt', '237.txt', '593.txt'], 'FileNotFoundError': ['987.txt']}

我必须使用get()命令,因为我得到了一个KeyError,这在技术上应该可行。如果我在解释器中逐行执行此操作。但由于某种原因,在脚本中,read_failures.get(error,[])方法返回None作为默认值而不是我指定的空列表。是否有一个版本的Python,默认的get return不是什么?

谢谢!

2 个答案:

答案 0 :(得分:2)

正如其他评论和解答所指出的,您的问题是list.append会返回None,因此您无法将回调结果分配回字典。但是,如果列表已经在字典中,则不需要重新分配,因为append将对其进行修改。

所以问题是,如果还没有新的列表,你怎么能在字典中添加一个新的列表呢?原始修复方法是使用单独的if语句:

if error not in read_failures:
    read_failures[error] = []
read_failures[error].append(filename)

但是这需要在字典中最多三次查找密钥,我们可以做得更好。 dict类有一个名为setdefault的方法,用于检查给定键是否在字典中。如果不是,它将为键分配给定的默认值。无论如何,将返回字典中的值。所以,我们可以用一行来完成整个事情:

read_failures.setdefault(error, []).append(filename)

另一种替代解决方案是使用defaultdict对象(来自标准库中的collections模块)而不是普通字典。 defaultdict构造函数采用factory参数,只要请求的密钥尚未存在,就会调用该参数来创建默认值。

所以另一个实现是:

from collections import defaultdict

read_failures = defaultdict(list)
for filename in files:
    try:
        // open file
    except Exception as e:
        error = type(e).__name__
        read_failures[error].append(filename)

答案 1 :(得分:0)

所以这个

0x00000001 << i

将read_failures [error]的值设置为None,因为.append方法返回None。简单的解决方法是将其更改为:

read_failures[error] = read_failures.get(error, []).append(filename)

谢谢user2357112!