简体   繁体   English

附加到字典中的列表

[英]Appending to a list inside of a dictionary

I'm going through a list of individual words and creating a dictionary where the word is the key, and the index of the word is the value. 我正在浏览各个单词的列表,并创建一个词典,其中单词是键,而单词的索引是值。

dictionary = {}
for x in wordlist:
    dictionary[x] = wordlist.index(x)

This works fine at the moment, but I want more indexes to be added for when the same word is found a second, or third time etc. So if the phrase was "I am going to go to town", I would be looking to create a dictionary like this: 目前,这可以正常工作,但是我希望在第二次或第三次发现相同单词时添加更多索引。因此,如果该短语是“我要去城镇”,我将寻找创建一个这样的字典:

{'I': 0, 'am' : 1, 'going' : 2, 'to': (3, 5), 'go' : 4, 'town' : 6}

So I suppose I need lists inside the dictionary? 所以我想在字典中需要列表吗? And then to append more indexes to them? 然后向它们附加更多索引? Any advice on how to accomplish this would be great! 关于如何实现这一目标的任何建议都将是很棒的!

You can do this way: 您可以这样做:

dictionary = {}
for i, x in enumerate(wordlist):
    dictionary.setdefault(x, []).append(i)

Explanation: 说明:

  • You do not need the call to index() . 您不需要调用index() It is more efficient and cooler to use enumerate() . 使用enumerate()更高效,更酷。
  • dict.setdefault() uses the first argument as key. dict.setdefault()使用第一个参数作为键。 If it is not found, inserts the second argument, else it ignores it. 如果找不到,则插入第二个参数,否则将忽略它。 Then it returns the (possibly newly inserted) value. 然后,它返回(可能是新插入的)值。
  • list.append() appends the item to the list. list.append()将项目追加到列表中。

You will get something like this: 您将获得如下内容:

{'I': [0], 'am' : [1], 'going' : [2], 'to': [3, 5], 'go' : [4], 'town' : [6]}

With lists instead of tuples, and using lists even if it is only one element. 使用列表而不是元组,并使用列表,即使它只是一个元素。 I really think it is better this way. 我真的认为这样更好。

UPDATE : 更新

Inspired shamelessly by the comment by @millimoose to the OP (thanks!), this code is nicer and faster, because it does not build a lot of [] that are never inserted in the dictionary: @millimoose对OP的评论无耻地启发了(谢谢!),这段代码更好,更快,因为它并没有建立很多从未插入到字典中的[]

import collections
dictionary = collections.defaultdict(list)
for i, x in enumerate(wordlist):
    dictionary[x].append(i)
>>> wl = ['I', 'am', 'going', 'to', 'go', 'to', 'town']
>>> {w: [i for i, x in enumerate(wl) if x == w] for w in wl}
{'town': [6], 'I': [0], 'am': [1], 'to': [3, 5], 'going': [2], 'go': [4]}

Objects are objects, regardless of where they are. 对象是对象,无论它们在哪里。

dictionary[x] = []
 ...
dictionary[x].append(y)

A possible solution: 可能的解决方案:

dictionary= {}
for i, x in enumerate(wordlist):
    if not x in dictionary : dictionary[x]= []
    dictionary[x].append( i )
import collections
dictionary= collections.defaultdict(list)
for i, x in enumerate( wordlist ) : 
    dictionary[x].append( i )

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

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