Home > front end >  How can I create a nested dictionary inside a nested dictionary via for loop?
How can I create a nested dictionary inside a nested dictionary via for loop?

Time:08-04

how can i create something like this

in the kitchen  :  {'2010-01-05': {'activity': '...', 'activity':'...', 'activity':'...'}, '2010-01-06':{'activity':'...', 'activity':'...'}}

if my list looks like this?

my_list= [
    ['2010-01-05 12:32:05', 'in the kitchen', 'ON'],
    ['2010-01-05 12:32:08', 'in the kitchen', 'ON'],
    ['2010-01-05 12:32:10', 'in the kitchen', 'ON'],
    ['2010-01-06 02:32:11', 'in the kitchen', 'ON'],
    ['2010-01-06 02:32:20', 'in the kitchen', 'ON']]

i already have all the information i want to insert after 'activity', i just need a snippet on how could i achive this kind of output. i tried doing this

my_Dict= {}
for i, item in enumerate(my_list): 
..... # calculating for every item the info i want to put in my dict .....
 res = str(time)
 p = item[0].split()  # because i only want the date as key, not also the time
 if item[1] not in my_Dict.keys():
        my_Dict[item[1]] = dict()
           if item[0] not in my_Dict.keys():
               my_Dict[item[1]][p[0]] = dict()

               my_Dict[item[1]][p[0]]["activity"] = res

but the output it gives is

in the kitchen  :  {'2010-01-05': {'activity': '...'}}

not considering the other times the sensor was active and not considering even the next day of activity, it just consider the first element

CodePudding user response:

You're trying to use dictionary when what you probably need is a List.

You'll have to use List of dictionary, which means your data should look like :

in the kitchen  :  {'2010-01-05': [{'activity': '...'}, {'activity':'...'}, {'activity':'...'}], '2010-01-06':[{'activity':'...'}, {'activity':'...'}] }

so your code would probably look similar to

my_dict["2010-01-05"].append({"activity" : res})

where my_dict["2010-01-05"] should be initialized as list as needed.

CodePudding user response:

I'd use a defaultdict for that. It allows you to directly modify dictionary values without the need to perform if x in dict checks.

from collections import defaultdict

# nested dict: {'location': {'date': ['action']}}
result = defaultdict(lambda: defaultdict(list))

for date, location, activity in my_list:
    result[location][date.split()[0]].append(activity)

The result looks like this and works like a regular nested dict.

defaultdict(<function __main__.<lambda>()>,
            {'in the kitchen': defaultdict(list,
                         {'2010-01-05': ['ON', 'ON', 'ON'],
                          '2010-01-06': ['ON', 'ON']})})
  • Related