1

可能一个例子会更容易解释这一点。

所以想象我有这样的事情:

 word_dict = {"word": frequency}

例如,我是否会循环遍历一个段落,在该段落中我发现单词 freq 为

 word_dict = {"this":2,"that":4} # assume that all the cases have just these two words..

是的,它是一个奇怪的字典..

现在,每个段落都分配给一个故事,这个故事有一个 id:

可以说我明白了:

{1234: {word_dict}} # where 1234 is the story id

然后这个故事被包含在一本书中:所以如果做类似的事情book_dict[book_id][story_id],这将返回我 word_dict。

但是很有可能相同的 book_id、story_id 会有不同的 word_dict

我知道这听起来很奇怪..

所以我想要的是book_dict[book_id][story_id] = [{word_dict}]它返回我一个单词字典列表..

我该如何实现这一点。

呃。这个问题有意义吗?

4

3 回答 3

3
book_dict = {}
for each book_id, story_id, word_dict in who_knows_what:
    if book_id not in book_dict:
        book_dict[book_id] = {}
    if story_id not in book_dict[book_id]:
        book_dict[book_id][story_id] = []
    book_dict[book_id][story_id].append( word_dict )
于 2012-04-15T23:15:22.720 回答
3

另一种选择是使用setdefault

book_dict = {}
for each book_id, story_id, word_dict in who_knows_what:
    book_dict.setdefault(book_id, {}).setdefault(story_id, []).append(word_dict) 
于 2013-09-17T17:48:45.873 回答
2

这是 Scott Hunter 答案的简化版本:

book_dict = {}
for book_id, story_id, word_dict in who_knows_what:
    book_dict[book_id] = book_dict.get(book_id, {})
    book_dict[book_id][story_id] = book_dict[book_id].get(story_id, [])
    book_dict[book_id][story_id].append( word_dict )
于 2013-09-17T17:41:41.813 回答