在Python中为字典中的值制作字典
我正在尝试添加字典,这些字典具有来自列表中每个元素的键和来自列表中一个后续元素的值,以及字典格式的跟随次数计数。例如,如果我们有单词列表,在Python中为字典中的值制作字典,python,dictionary,Python,Dictionary,我正在尝试添加字典,这些字典具有来自列表中每个元素的键和来自列表中一个后续元素的值,以及字典格式的跟随次数计数。例如,如果我们有单词列表,['the','cat','chased','the','dog']并且如果键是“the”,我希望值是{'dog':1,'cat':1}。整个输出应该是{'The':{'dog':1,'cat':1},'chased':{'The':1},'cat':{'chased':1} 到目前为止,我的代码可以生成键和值,但不能以字典格式生成字典。有人能帮忙吗 我的代码
['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)
输出:
{'The': 'cat', 'chased': 'the', 'the': 'dog', 'cat': 'chased'}
你可以用这个。范例-
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)
.setdefault()
首先检查该键是否存在,如果不存在,则将其设置为第二个参数,然后返回该键处的值
在计数器中,当您执行.update()
时,如果密钥已经存在,它会将计数增加1,因此这似乎是用于您的案例的正确结构
而且,计数器的行为和普通字典一样,所以以后您可以像使用任何字典一样使用它们
演示(请注意修改后的输入,以显示
'dog'
紧跟'the'
两次的场景)-
我没有测试它,但类似的东西可能?使用
defaultdict
:
看起来给您带来麻烦的线路是以下线路:
output[item] = line[i+1]=i
看起来您没有考虑到输出[item]应该指向字典。看起来您需要将单词小写,以便正确比较
我能够通过以下代码获得您想要的输出:
line = ['The', 'cat', 'chased', 'the', 'dog']
output = {}
length = len(line) # I didn't wanted to check this each iteration
for i, item in enumerate(line):
item = item.lower()
if i != length - 1:
next_word = line[i + 1].lower()
if item in output:
output[item][next_word] = 1
else:
output[item] = {next_word: 1}
print(output)
我不明白你是如何建立输出的。。请您解释一下好吗?首先,将
output[item]=line[i+1]=i
更改为output[item]=line[i+1]
,否则将无法显示输出。在这里,您需要首先检查该项是否已作为密钥存在。然后,如果没有,用{line[i+1]:1}创建一个dict。如果是,只需将1添加到相应的值。[…]等等,刚才看到你想要{'the':{'dog':1,'cat':1}…
。那就有点不同了。1分钟不应该'dog':{'the'}
也在dict中吗?紧随其后的狗
,我稍微修改了输入以显示更复杂的场景。请不要将输出与OP问题的输入进行比较,与演示中的实际输入进行比较。我明白了,很抱歉没有注意到输入的差异。
output[item] = line[i+1]=i
line = ['The', 'cat', 'chased', 'the', 'dog']
output = {}
length = len(line) # I didn't wanted to check this each iteration
for i, item in enumerate(line):
item = item.lower()
if i != length - 1:
next_word = line[i + 1].lower()
if item in output:
output[item][next_word] = 1
else:
output[item] = {next_word: 1}
print(output)