0

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.

Pythonist
  • 677
  • 5
  • 28
  • I don't think `'name': [users][user]['name'],` is valid python syntax. But `collections.defaultdict` or `dict.setdefault` may be good alternatives to these `if xxx not in yyy` statements. – MSeifert Dec 29 '16 at 14:53
  • this should answer your questions: https://stackoverflow.com/questions/19189274/defaultdict-of-defaultdict-nested#19189356 – hiro protagonist Dec 29 '16 at 14:54
  • You're right sir, that's my misspelling, should be `users[user]['name]`. Will check linked answer, thank you. – Pythonist Dec 29 '16 at 14:56

1 Answers1

-2

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
wildwilhelm
  • 4,809
  • 1
  • 19
  • 24