python - 在一行中声明并附加字典中的列表

标签 python dictionary

我想知道是否有一个字典命令允许我声明一个键并列表(如果它不在字典中),或者更新它(如果在)。

i = 0
newlines["numbersbytwo"] = []
newlines["numbersbyfive"] = []
while i<n:
    newlines["numbersbytwo"].append(i*2)
    newlines["numbersbyfive"].append(i*5)
    i+=1

这是我目前的代码,但我想知道是否有任何方法可以不必先声明它。

最佳答案

您可以使用defaultdict以空列表作为默认值。例如:

In [1]: from collections import defaultdict

In [2]: newlines = defaultdict(list)

In [3]: newlines["numbersbytwo"].append(1)

In [4]: newlines["numbersbyfive"].append(11)

In [5]: newlines
Out[5]: defaultdict(<function <lambda> at 0x00000000031D5048>, {'numbersbyfive': [11], 'numbersbytwo': [1]})

In [6]: newlines["numbersbytwo"]
Out[6]: [1]

In [7]: newlines["numbersbyfive"]
Out[7]: [11]

In [8]:

关于python - 在一行中声明并附加字典中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25446104/

相关文章:

python - 使用终端将时间戳输出到日志文件

python - 了解 django 文档代码 - session

scala - 在scala中将文件的内容存储在不可变的Map中

python - 更改Python字典中键的值

python - matplotlib 中的颜色

python - 用字母代替数字的 for 循环

python - 在 Python 字典中查找最接近的值并返回其键

python - 将作为值存储在嵌套字典中的 Python 列表聚合到任意级别的一个列表中

python - ipython 中的选项卡完整字典键

python - 属性错误: Can't pickle local object 'computation.。使用多处理队列的 function1