简体   繁体   English

如何在python中一次将两个值附加到字典?

[英]How to append two values to a dictionary at once in python?

I don't think the title really explains it, but here's the problem. 我认为标题并不能真正说明问题,但这是问题所在。

My code is this (Python 2.7): 我的代码是这样的(Python 2.7):

    Dict = {}
    for i in range(0, 6):
        for j in range(0, 7):
            Dict[i][j] = 0;
    return Dict;

But I always get KeyError: 0. 但是我总是得到KeyError:0。

Here, set one at a time: 在这里,一次设置一个:

mydict = {}
for i in range(0, 6):
    mydict[i] = {}

    for j in range(0, 7):
        mydict[i][j] = 0

return mydict

That is, if you want something like this: 也就是说,如果您想要这样的话:

{
    0:{
        0: 0,
        // ...
    },
    // ...
}

The problem you were running into is that you were trying to set an item of an item, before defining what the i-th item was. 您遇到的问题是,在定义第i个项目之前,您试图设置一个项目。

Use a defaultdict: 使用defaultdict:

from collections import defaultdict

a = defaultdict(dict)

for i in range(0, 6):
    for j in range(0, 7):
        a[i][j] = 0

In python you have to explicitly define each index in a dictionary. 在python中,您必须明确定义字典中的每个索引。 You can have them auto created for you like this 您可以像这样自动为他们创建

import collections
auto_dict = lambda: collections.defaultdict(auto_dict)

my_dict = auto_dict()
my_dict['lvl1']['lvl2'] = 1
print my_dict['lvl1']['lvl2']
# 1

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

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