[英]dicts and nested dicts python
Attempting to understand dicts in a somewhat simple way I believe, but am thoroughly confused.我相信试图以一种简单的方式理解dicts,但我完全糊涂了。 When I run the code below, it works fine to populate dict and count the occurrences of a word.
当我运行下面的代码时,它可以很好地填充 dict 并计算单词的出现次数。 Output is as such:
{'gerry': 2, 'babona': 1, 'cheese': 1, 'cherry': 1}
Output 是这样的:
{'gerry': 2, 'babona': 1, 'cheese': 1, 'cherry': 1}
dict = {}
a = ['gerry', 'babona', 'cheese', 'gerry', 'cherry']
b = ['O' ,'O', 'T', 'T', 'T']
for (i,j) in zip(a,b):
if i not in dict:
dict[i] = 1
else:
dict[i] += 1
However, if I try to run the following code, there is a KeyError: 'gerry'
, beginning with the first value in the list, but I cannot make sense of why.但是,如果我尝试运行以下代码,则会出现
KeyError: 'gerry'
,从列表中的第一个值开始,但我无法理解原因。 Any help on this greatly appreciated!非常感谢您对此的任何帮助!
dict = {}
a = ['gerry', 'babona', 'cheese', 'gerry', 'cherry']
b = ['O' ,'O', 'T', 'T', 'T']
for (i,j) in zip(a,b):
if i not in dict:
dict[i][j] = 1
else:
dict[i][j] += 1
The first example can be simpler第一个例子可以更简单
from collections import Counter
a = ['gerry', 'babona', 'cheese', 'gerry', 'cherry']
data = Counter(a)
For second第二个
from collections import defaultdict
a = ['gerry', 'babona', 'cheese', 'gerry', 'cherry']
b = ['O', 'O', 'T', 'T', 'T']
data = defaultdict(lambda: defaultdict(int))
for (i, j) in zip(a, b):
data[i][j] += 1
btw don't use reserved name for your variable eg dict
顺便说一句,不要为您的变量使用保留名称,例如
dict
When the program gets to: dict[i][j] = 1
it has to execute: dict[i]
first, which is exactly what you were trying to avoid when you wrote the first snippet.当程序到达:
dict[i][j] = 1
时,它必须首先执行: dict[i]
,这正是您在编写第一个代码段时试图避免的。
You will have to do multi-stage tests to get this to work.您必须进行多阶段测试才能使其正常工作。
You can get it to work like this, but there are simpler ways:你可以让它像这样工作,但有更简单的方法:
dct = {}
a = ['gerry', 'babona', 'cheese', 'gerry', 'cherry']
b = ['O' ,'O', 'T', 'T', 'T']
for (i,j) in zip(a,b):
if i not in dct:
dct[i] = {}
dct[i][j] = 1
else:
di = dct[i]
if j not in di:
di[j] = 0
dct[i][j] += 1
print(dct)
Output: Output:
{'gerry': {'O': 1, 'T': 1}, 'babona': {'O': 1}, 'cheese': {'T': 1}, 'cherry': {'T': 1}}
from collections import Counter
a = ['gerry', 'babona', 'cheese', 'gerry', 'cherry']
b = ['O' ,'O', 'T', 'T', 'T']
print(Counter(a))
Counter({'gerry': 2, 'babona': 1, 'cheese': 1, 'cherry': 1})
for the 2nd case you can use groupby
对于第二种情况,您可以使用
groupby
dct = dict((key, tuple(v for (k, v) in pairs))
for (key, pairs) in groupby(sorted(zip(a,b)), lambda pair: pair[0]))
{k:Counter(v) for k,v in dct.items()}
{'babona': Counter({'O': 1}), 'cheese': Counter({'T': 1}),'cherry': Counter({'T': 1}), 'gerry': Counter({'O': 1, 'T': 1})}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.