简体   繁体   中英

Creating a nested dictionary python

Probably an example will be easier to explain this.

So imagine i have something like this:

 word_dict = {"word": frequency}

example would I loop thru a paragraph and in that paragraph I found the word freq as

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

yepp its a strange dict..

Now, each paragraph is assigned to a story and this story has an id:

lets say i get this:

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

and then this story is contanined in a book: So if do something like book_dict[book_id][story_id] , this would return me word_dict.

But there is a good chance that a same book_id, story_id will have different word_dict

i Know it sounds weird..

So what I want is that book_dict[book_id][story_id] = [{word_dict}] so it returns me a list of word dictionary..

How do I implement this.

Err. is the question making any sense?

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 )

Another option is using 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) 

Here's a shortened version of the answer by 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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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