[英]How can I generate a dictionary of lists in python?
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其中“时间”是 pandas 日期时间,但它给出的 output 是
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不考虑传感器处于活动状态的其他时间
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): Output(my_dict):
{'in the kitchen': {'2010-01-05': [{'activity': 'ON'}, {'activity': 'ON'}, {'activity': 'ON'}], '2010-01-06': [{'activity': 'ON'}, {'activity': 'ON'}]}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.