1

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'

1
  • Use a list as the value. That way you can append subsequent entries to the appropriate list Commented Dec 6, 2017 at 9:01

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

3 Comments

this seems to be doing it yeah, thank you. defaultdict(list) just sets the value field to list ? and is it possible to sort the list in the same line or does it have to be done in another line ?
sets the value field to automatically be an empty list, otherwise you have to do an approach like Veltz where you check if it is a list first.
I would only sort the lists after you've finished fully creating the dictionary (for efficiency). [v.sort() for v in dicta.values()] sorts the lists, but doesn't return anything. (so don't do dicta = [v.sort.....)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.