Add new data to existing dictionary

I want to add new data in the existing dictionary. I tried using update but it is not working for me. What to do?


comp_data = {}
temp =
print('nTemp: ', temp)
for i in temp:
    print('i : ', i)

print("nnComp Data : ", comp_data)


Temp:  [{'question': 'q1', 'option1': 'q1', 'option2': 'q1', 'option3': 'q1', 'answer': 'q1'}, {'question': 'q2', 'option1': 'q2', 'option2': 'q2', 'option3': 'q2', 'answer': 'q2'}]

i : {'question': 'q1', 'option1': 'q1', 'option2': 'q1', 'option3': 'q1', 'answer': 'q1'}
i : {'question': 'q2', 'option1': 'q2', 'option2': 'q2', 'option3': 'q2', 'answer': 'q2'}

Comp Data :  {'question': 'q2', 'option1': 'q2', 'option2': 'q2', 'option3': 'q2', 'answer': 'q2'}

The output i want is like this:

Comp Data :  {{'question': 'q1', 'option1': 'q1', 'option2': 'q1', 'option3': 'q1', 'answer': 'q1'}, {'question': 'q2', 'option1': 'q2', 'option2': 'q2', 'option3': 'q2', 'answer': 'q2'}}


You already have your desired output in temp

Temp:  [{'question': 'q1', 'option1': 'q1', 'option2': 'q1', 'option3': 'q1', 'answer': 'q1'}, {'question': 'q2', 'option1': 'q2', 'option2': 'q2', 'option3': 'q2', 'answer': 'q2'}]

Comp Data :  {'question': 'q1', 'option1': 'q1', 'option2': 'q1', 'option3': 'q1', 'answer': 'q1'}, {'question': 'q2', 'option1': 'q2', 'option2': 'q2', 'option3': 'q2', 'answer': 'q2'}

Dictionary is not a typical container that you can index , it works on the principles of KEY –> VALUE pairs and cannot contain duplicate keys

I would suggest you to directly use temp for your further usage in your code

Based on your edit –

if you still want to create a new dictionary you can do that as follows –

>>> t = [{'question': 'q1', 'option1': 'q1', 'option2': 'q1', 'option3': 'q1', 'answer': 'q1'}, {'question': 'q2', 'option1': 'q2', 'option2': 'q2', 'option3': 'q2', 'answer': 'q2'}]
>>> d = {}
>>> for i,k in enumerate(t):
...     d[i] = k
>>> from pprint import pprint
>>> pprint(d)
{0: {'answer': 'q1',
     'option1': 'q1',
     'option2': 'q1',
     'option3': 'q1',
     'question': 'q1'},
 1: {'answer': 'q2',
     'option1': 'q2',
     'option2': 'q2',
     'option3': 'q2',
     'question': 'q2'}}

Leave a Reply

Your email address will not be published. Required fields are marked *