问题描述
我有一个字典,其中键是字符串,值是列表.
现在在添加与给定键关联的值时,我总是必须检查是否有任何列表,否则我必须像以下代码段一样初始化为空列表:
如果在 myDict 中不是 k:myDict[k] = []myDict[k].append(v)
我想知道是否有任何方法可以在 python 3.7 中将这些步骤合并为一个.
至少有三种方式:
使用dict.setdefault
使用 defaultdict
,它不像 .setdefault
,需要一个可调用的:
最后,子类dict
并实现__missing__
:
注意,您可以认为最后一个是最灵活的,您可以访问处理它时丢失的实际密钥.defaultdict
是一个类工厂,它也生成一个 dict
的子类.但是,callable 没有传递任何参数,不过,它足以满足大多数需求.
此外,请注意 defaultdict
和 __missing__
方法将保持默认行为,这在您创建数据结构后可能是不可取的,您可能想要 一个 KeyError
通常,或者至少,你不希望 mydict[key]
再添加一个键.
在这两种情况下,您都可以从 dict 子类中创建一个常规的 dict,例如dict(data)
.这通常应该非常快,即使对于大型 dict
对象,尤其是如果它是一次性成本.对于defaultdict
,您还可以将default_factory
设置为None
,然后旧行为返回:
I have a dictionary where key is string and value is list.
Now while adding a value associated with given key, I always have to check if there is any list yet, otherwise I have to initialize as empty list somewhat like following snippet:
if not k in myDict:
myDict[k] = []
myDict[k].append(v)
I am wondering if there is any way to combine these steps into single one in python 3.7.
There are at least three ways:
Use dict.setdefault
>>> data = {}
>>> data.setdefault('foo', []).append(42)
>>> data
{'foo': [42]}
Use defaultdict
, which unlike .setdefault
, takes a callable:
>>> from collections import defaultdict
>>> data = defaultdict(list)
>>> data
defaultdict(<class 'list'>, {})
>>> data['foo'].append(42)
>>> data
defaultdict(<class 'list'>, {'foo': [42]})
Finally, subclass dict
and implement __missing__
:
>>> class MyDict(dict):
... def __missing__(self, key):
... self[key] = value = []
... return value
...
>>> data = MyDict()
>>> data['foo'].append(42)
>>> data
{'foo': [42]}
Note, you can think of the last one as the most flexible, you have access to the actual key that's missing when you deal with it. defaultdict
is a class factory, and it generates a subclass of dict
as well. But, the callable is not passed any arguments, nevertheless, it is sufficient for most needs.
Further, note that the defaultdict
and __missing__
approaches will keep the default behavior, this may be undesirable after you create your data structure, you probably want a KeyError
usually, or at least, you don't want mydict[key]
to add a key anymore.
In both cases, you can just create a regular dict from the dict subclasses, e.g. dict(data)
. This should generally be very fast, even for large dict
objects, especially if it is a one-time cost. For defaultdict
, you can also set the default_factory
to None
and the old behavior returns:
>>> data = defaultdict(list)
>>> data
defaultdict(<class 'list'>, {})
>>> data['foo']
[]
>>> data['bar']
[]
>>> data
defaultdict(<class 'list'>, {'foo': [], 'bar': []})
>>> data.default_factory = None
>>> data['baz']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'baz'
>>>
这篇关于在 Python 3.7 中一步初始化并将值添加到字典中的列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!