Search code examples
pythondictionarynested-loops

Loop creating nested dicts


I'm importing data from CSV and placing it in nested dicts. My current key-checking looks like this:

data = {}
[...]
if day not in data:
    data[day] = {}
if hour not in data[day]:
    data[day][hour] = {}
if user in data[day][hour]:
    worked_time += (
        data[day][hour][user]['worked_time']
    )
data[day][hour][user] = {
    'name': users[user]['name'],
    'worked_time': worked_time
}

They can be several users for each data[day][hour]
Was wondering if there's better way for checking if each key exists than using several ifs.


Solution

  • collections.defaultdict is nice. If a dict doesn't have a value for the key you specify, it creates a new one for you.

    from collections import defaultdict
    data = defaultdict(lambda: defaultdict(lambda: defaultdict(dict)))
    data['day']['hour']['user']['worked_time'] = 2