Python:将列表更新为字典值

标签 python python-3.x

我想将列表作为字典的值,并希望能够在键匹配时追加到这些列表。

我知道当列表预定义如下时我可以做到这一点:

hashmap = {}
k = [1,2,3]
val = ['a','b','c']
for i in k:
    hashmap[i]= val
for j in hashmap.keys():
    print(hashmap[j])

但是如果没有定义val列表的内容怎么办。我如何在运行时声明它并将其附加到那些列表?

最佳答案

如果列表不存在,则使用 defaultdict 创建列表:

from collections import defaultdict

dd = defaultdict(list)
dd['a'].append(1)  # create the list if it doesn't exist
print(dd)
# defaultdict(<class 'list'>, {'a': [1]})

关于Python:将列表更新为字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48511379/

相关文章:

python - 如何使用 discord.py 事件处理程序 on_voice_state_update 仅在用户加入语音 channel 时运行

python - 如何在sql语句的python字符串中使用通配符%

python - 什么定义了 python 中的浮点精度?

python - 如何在django中显示数据库中的视频在主页上

python - 查找与完整集具有相似均值的子集

python - 将延迟加载与 DRF 结合使用

python - 如何计算 pandas 数据框中两个或多个非零元素之间的最小间隙?

python - 如何在图表区的 Python-pptx 图表中为图表提供图表标题(不是幻灯片标题)

python-3.x - 为什么网格只在最后一个子图上打开?

Python 将单行转置为列