Home > Software design >  How can I generate a dictionary of lists in python?
How can I generate a dictionary of lists in python?

Time:08-20

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:07', 'in the living room', 'ON'],
    ['2010-01-05 12:32:08', 'in the kitchen', 'ON'],
    ['2010-01-05 12:32:09', 'in the living room', 'ON'],
    ['2010-01-05 12:32:10', 'in the kitchen', 'ON'],
    ['2010-01-06 02:32:11', 'in the kitchen', 'ON'],
    ['2010-01-05 02:32:15', 'in the living room', 'ON'],
    ['2010-01-05 02:32:17', 'in the living room', 'ON'],
    ['2010-01-06 02:32:20', 'in the kitchen', 'ON']]

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():  # creo un altro dizionario con key la data
              my_Dict[item[1]][p[0]] = defaultdict(list)
              my_Dict[item[1]][p[0]]["activity"].append(res)

where "time" is pandas datetime, but the output it gives is

in the kitchen  :  {'2010-01-05': defaultdict(<class 'list'>, {'attività': ['0 days 00:00:01']}), '2010-01-06': defaultdict(<class 'list'>, {'attività': ['0 days 00:00:09']})}

in the living room  :  {'2010-01-05': defaultdict(<class 'list'>, {'attività': ['0 days 00:00:03']})}

not considering the other times the sensor was active

CodePudding user response:

Does this answer your question?

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']
]

my_dict = {}
for datetime, location, activity in my_list:
    date, time = datetime.split()
    my_dict.setdefault(location, {})
    my_dict[location].setdefault(date, [])
    my_dict[location][date].append({"activity": activity})

Output (my_dict):

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