创建嵌套字典python

时间:2012-04-15 23:06:40

标签: python

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

想象一下我有这样的事情:

 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}]所以它会返回一个单词词典列表..

我该如何实现呢。

ERR。问题是否有意义?

3 个答案:

答案 0 :(得分: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 )

答案 1 :(得分: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) 

答案 2 :(得分: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 )