I have the following problem. I want to automatically create with a for function a dictionary with mixed keys as following:
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.
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)