i33SoDA
i33SoDA

Reputation: 75

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 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.

Upvotes: -1

Views: 55

Answers (2)

cards
cards

Reputation: 4986

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)

Upvotes: 2

parsariyahi
parsariyahi

Reputation: 318

your bug is you override store_dict each loop, that's why you are getting just one element,

Here is the code you want:

store_dic= dict()

# result = {
#     "books": {
#         "book0": 0,
#         "book1": 1,
#         "book2": 2,
#     }
# }

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

print(store_dic)

The output :

{'books': {'book0': 0, 'book1': 1, 'book2': 2}}

Upvotes: 1

Related Questions