简体   繁体   English

如何通过 for 循环在嵌套字典中创建嵌套字典?

[英]How can I create a nested dictionary inside a nested dictionary via for loop?

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.我已经有了我想在“活动”之后插入的所有信息,我只需要一个关于如何获得这种 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但它给出的 output 是

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不考虑传感器处于活动状态的其他时间,甚至不考虑第二天的活动,它只考虑第一个元素

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.其中my_dict["2010-01-05"]应根据需要初始化为列表。

I'd use a defaultdict for that.我会为此使用defaultdict It allows you to directly modify dictionary values without the need to perform if x in dict checks.它允许您直接修改字典值,而无需执行if x in dict检查。

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 .结果看起来像这样,并且像常规的嵌套dict一样工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM