0

I can't figure out how to update a value in a nested dictionary, the value keeps getting overwritten.

I have a list date_list = ['2018AUG15', '2017APR22', '2017MAR05', '2016FEB10', '2016FEB09']

I'm working on building a nested dict and so far I have

import collections

date_list = ['2018AUG15', '2017APR22', '2017MAR05', '2016FEB10', '2016FEB09']
month_ditc = collections.defaultdict(dict)

for x in date_list:

    year = x[:4]
    month = x[4:-2]
    day = x[7:]

    month_ditc[year][month]= day

print month_ditc

which yields

defaultdict(<type 'dict'>, {'2017': {'APR': '22', 'MAR': '05'}, '2016': {'FEB': '09'}, '2018': {'AUG': '15'}})

This is close to what I want. The year and month are updating as I loop through, but the day is not.

I have tried the following but still nothing -

 try:
     month_ditc[year][month] = day
 except KeyError:
     month_ditc[year] = {month:day}

I would like the result to be

defaultdict(<type 'dict'>, {'2017': {'APR': '22', 'MAR': '05'}, '2016': {'FEB': '09','10'}, '2018': {'AUG': '15'}})
6
  • 1
    Can you show what you expect? Commented Apr 17, 2017 at 13:57
  • What is ordered_string_list ? Commented Apr 17, 2017 at 13:59
  • @TrakJohnson sorry, should be date_list. I changed the body Commented Apr 17, 2017 at 14:02
  • @MosesKoledoye I updated the body. If there are multiple days in the same month. I need that reflected in the dict. Commented Apr 17, 2017 at 14:05
  • Looks like you want to append the days to a list? Commented Apr 17, 2017 at 14:07

1 Answer 1

4

Your expected output is not valid dictionary, I suppose you want a list, you can try to use setdefault() method to set default value if key is not already in dict.

setdefault(key[, default])

If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

import collections

date_list = ['2018AUG15', '2017APR22', '2017MAR05', '2016FEB10', '2016FEB09']
month_ditc = collections.defaultdict(dict)

for x in date_list:

    year = x[:4]
    month = x[4:-2]
    day = x[7:]

    month_ditc[year].setdefault(month, []).append(day)
print dict(month_ditc)

Result:

{'2017': {'APR': ['22'], 'MAR': ['05']}, '2016': {'FEB': ['10', '09']}, '2018': {'AUG': ['15']}}
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I needed, thank you for the clear explanation.

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.