Search code examples
pythondictionarykeymixed

How to automatically add new keys with values to an existing key?


I have the following problem. I want to automatically create with a for function a dictionary with mixed keys as following:

  • I have the main key which is "books" and for this key I want to add books ( which a new key ) with quantity ( values ) Example: store_dic = {'books': {'book0': 0, 'book1': 1,'book2':2}}

I tried this:

store_dic= dict()

book_list = [[None] for _ in range(3)]
for i in range(3):
    book_list[i] = "book"+str(i)
    store_dic= {'books': {book_list[i] : i}}
print(store_dic)

Currently the dictionary displays only the last key with value inserted in the main key.

Output
{'books': {'book2': 2}}

Please help me update the main key with multiple keys that have values.


Solution

  • A possibility could be to divide the task into two steps, first create the mapping with "enumerated" books then assign it to you main dictionary.

    book_list = [[None] for _ in range(3)]
    
    store_dic = dict()
    books = {'book'+str(k): k for k in range(len(book_list))}
    store_dic['books'] = books
    

    ... or a more compact version

    book_list = [[None] for _ in range(3)]
    
    store_dic = {}
    
    for i in range(len(book_list)):
        store_dic.setdefault('books', {})['book'+str(i)] = i
    

    or with a dictionary comprehension

    book_list = [[None] for _ in range(3)]
    
    store_dic = {
        'books': {'book'+str(i): i for i in range(len(book_list))}
    }
    

    Notice that you could use the f-string notation to improve readability, f'book{i}' instead of 'book'+str(i)