【问题标题】:Python: updating a list as a dictionary valuePython:将列表更新为字典值
【发布时间】:2018-07-08 17:54:01
【问题描述】:

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

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

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 列表的内容没有定义呢?如何声明它运行时并附加到那些列表?

【问题讨论】:

  • 我不明白你的问题。如果 val 没有定义,你希望如何使用val?另请注意,这里没有 lists,您有一个 single list
  • @Orenshi 啊哈,是的,可能。

标签: python python-3.x


【解决方案1】:

如果列表不存在,请使用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]})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 2011-05-30
    • 1970-01-01
    • 2018-02-11
    • 2022-11-14
    相关资源
    最近更新 更多