Search code examples
pythondefaultdict

Append to dictionary in defaultdict


I have a defaultdict, I want to create a dictionary as the value part, can I append to this dictionary? At the moment I am appending to a list which means that the dictionaries are separated.

dates = [datetime.date(2016, 10, 17), datetime.date(2016, 10, 18), datetime.date(2016, 10, 19), datetime.date(2016, 10, 20), datetime.date(2016, 10, 21), datetime.date(2016, 10, 22), datetime.date(2016, 10, 23)]

e = defaultdict(list)
for key, value in d.iteritems():
    value = (sorted(value, key=itemgetter('date'), reverse=False))
    for date in dates:
        for i in value:
            if i['date'] == str(date) and i['time'] == 'morning':
                value1 = float(i['value1'])
                temp = {'val_morning': value1 }
                e[str(date)].append(temp)
            elif ii['date'] == str(date) and i['time'] == 'evening':
                value2 = float(i['value2'])
                temp = {'val_evening': value2 }
                e[str(date)].append(temp)

which results in:

{'2016-10-20': [{'val_morning': 0.0}, {'val_evening': 0.0}], '2016-10-21': [{'val_morning': 0.0}, {'val_evening': 0.0}]}

Edit desired output:

{                        
    '2016-10-20': {'val_morning': 0.0, 'val_evening': 0.0}, 
    '2016-10-21': {'val_morning': 0.0, 'val_evening': 0.0}
}

Solution

  • if i understood you correctly, you want to replace the list with a dict, that you can later add to it values.

    if so you can do this:

    dates = [datetime.date(2016, 10, 17), datetime.date(2016, 10, 18), datetime.date(2016, 10, 19), datetime.date(2016, 10, 20), datetime.date(2016, 10, 21), datetime.date(2016, 10, 22), datetime.date(2016, 10, 23)]
    
    e = defaultdict(dict)
    for key, value in d.iteritems():
        value = (sorted(value, key=itemgetter('date'), reverse=False))
        for date in dates:
            for i in value:
                if i['date'] == str(date) and i['time'] == 'morning':
                    value1 = float(i['value1'])
                    temp = {'val_morning': value1 }
                    e[str(date)].update(temp) #### HERE i replaced append with update!
                elif ii['date'] == str(date) and i['time'] == 'evening':
                    value2 = float(i['value2'])
                    temp = {'val_evening': value2 }
                    e[str(date)].update(temp)#### HERE i replaced append with update!
    

    i simply replaced the append with update (and of course made the defaultdict use dict instead of list)