在Python中为字典中的值创建字典

pyt*_*ner 6 python dictionary

我试图添加字典,其中列表中的每个元素都有一个键,列表中的一个后续元素的值和字典格式的后续次数的计数.例如,如果我们有单词列表,['The', 'cat', 'chased', 'the', 'dog']如果键是"the",我希望值为{'dog':1,'cat':1}.整个输出应该是{‘the’: {‘dog’: 1, ‘cat’: 1}, ‘chased’: {‘the’: 1}, ‘cat’: {‘chased’: 1}}.

到目前为止,我的代码可以生成键和值,但不能以字典格式生成字典.有人可以帮忙吗?

我的代码:

line = ['The', 'cat', 'chased', 'the', 'dog']
output = {}
for i, item in enumerate(line):
    print(i, item, len(line))
    if i != len(line) - 1:
        output[item] = line[i+1]=i
print(output)
Run Code Online (Sandbox Code Playgroud)

输出:

{'The': 'cat', 'chased': 'the', 'the': 'dog', 'cat': 'chased'}
Run Code Online (Sandbox Code Playgroud)

Ana*_*mar 2

您可以用于collections.Counter此用途。例子 -

line = ['The', 'cat', 'chased', 'the', 'dog','the','dog']
from collections import Counter
output = {}
for i, item in enumerate(line):
    print(i, item, len(line))
    if i != len(line) - 1:
        output.setdefault(item.lower(),Counter()).update(Counter({line[i+1]:1}))

print(output)
Run Code Online (Sandbox Code Playgroud)

.setdefault()首先检查该键是否存在,如果不存在,则将其设置为第二个参数,然后返回该键的值。

在 Counter 中,当您这样做时.update(),如果密钥已经存在,它会将计数增加 1 ,因此这似乎是适合您的情况的正确结构。

此外,Counter 的行为就像普通字典一样,因此您以后可以像任何字典一样使用它们。


'dog'演示(请注意修改后的输入以显示跟随两次的场景'the')-

>>> line = ['The', 'cat', 'chased', 'the', 'dog','the','dog']
>>> from collections import Counter
>>> output = {}
>>> for i, item in enumerate(line):
...     print(i, item, len(line))
...     if i != len(line) - 1:
...         output.setdefault(item.lower(),Counter()).update(Counter({line[i+1]:1}))
...
0 The 7
1 cat 7
2 chased 7
3 the 7
4 dog 7
5 the 7
6 dog 7
>>> print(output)
{'dog': Counter({'the': 1}), 'cat': Counter({'chased': 1}), 'chased': Counter({'the': 1}), 'the': Counter({'dog': 2, 'cat': 1})}
Run Code Online (Sandbox Code Playgroud)