python - 向python字典添加多个值

标签 python

我正在使用下面的代码检查一组具有日期和时间数据的字符串。如果存在字符串,我正在制作一本字典,其中包含基于月份中的某天的键。之后我想把那天的时间戳作为值。由于每天都有多个字符串,所以我希望一个键有多个值。

当前的代码能够为每一天生成一个带有数据的字符串,但是当添加时间戳时,它似乎每次都在覆盖它而不是添加它。如何向键添加多个值而不是每次都替换它。

for entry in data:
    month_year = entry[0:7]
    if month_year == month:
        day = entry[8:10]
        trigger_time = entry[11:19]
        print month_year
        dicta.update({day.encode("ascii"):[trigger_time]})
        #dicta[day.encode("ascii")].append[trigger_time]

注释行是一次尝试,但我收到此错误,AttributeError: 'int' object has no attribute 'append'

最佳答案

这就是字典的工作原理,给定键只能有一个值。

要实现您正在尝试做的事情,您可以使用列表作为值。

from collections import defaultdict
dicta = defaultdict(list) #<===== See here

for entry in data:
    month_year = entry[0:7]
    if month_year == month:
        day = entry[8:10]
        trigger_time = entry[11:19]
        print month_year
        dicta[day.encode("ascii")].append(trigger_time) #<===== See here

关于python - 向python字典添加多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47670273/

相关文章:

python - 类型错误 : read_hdf() takes exactly 2 arguments (1 given)

python - 合并 pandas 数据帧时出现数据类型错误

python - 匹配以两位或三位数字开头但不包含某处特定模式的事件

python - "returns iterator"在python中是什么意思?

python - 除非通过 CMD 输入,否则无法从 python 控制台导入模块

c# - 在多线程 C# 应用程序中嵌入 Python

python - 按列分组并将多个聚合作为数据框返回

python - tensorflow 中的 "y=x"和 y=tf.identity(x) 有什么区别

python - 将 datetime.date 的表示转换为 pandas.Timestamp 的表示

python - 控制台可以找到文件,但是使用运行工具窗口找不到