dmnte
dmnte

Reputation: 155

adding multiple values to python dictionary

I am using the code below to go over a bunch of strings that have date and time data. I am making a dictionary that has the keys based on the day in the month if there is a string present. After that I want to put the time-stamp for that day as the value. Since there are multiple strings for each day I want to have multiple values for one key.

The current code is able to make keys for each day were a string with data appears but when adding the time-stamp it seems to be writing over it each time and not adding to it. How can I add multiple values to the key rather than just replacing it each time.

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]

The commented line was an attempt but I get this error, AttributeError: 'int' object has no attribute 'append'

Upvotes: 1

Views: 132

Answers (1)

Anake
Anake

Reputation: 7669

That is how dictionaries work, there can only be one value for a given key.

To achieve what you are trying to do you can use a list as the value.

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

Upvotes: 4

Related Questions