0
import json

data={}
mdata={}

count=1
data['label'] ='person1'
data['confidence']='60'
mdata[count]=data
print(mdata)

data['label'] ='person2'
data['confidence']='50'
mdata[count+1]=data
print(mdata)

data['label'] ='person3'
data['confidence']='40'
mdata[count+2]=data

print(mdata)



Actual Output:
{1: {'label': 'person1', 'confidence': '60'}}
{1: {'label': 'person2', 'confidence': '50'}, 2: {'label': 'person2', 'confidence': '50'}}
{1: {'label': 'person3', 'confidence': '40'}, 2: {'label': 'person3', 'confidence': '40'}, 3: {'label': 'person3', 'confidence': '40'}}

Expected Output:
{1: {'label': 'person1', 'confidence': '60'}}
{1: {'label': 'person1', 'confidence': '60'}, 2: {'label': 'person2', 'confidence': '50'}}
{1: {'label': 'person1', 'confidence': '60'}, 2: {'label': 'person2', 'confidence': '50'}, 3: {'label': 'person3', 'confidence': '40'}}

I want to add dictionary inside a dictionary so that i can have multiple record as shown below. I have two record as shown above after creating each dict and adding new values to pervious dictionary i want to added it with new key values in mdata dictionary

1 Answers1

0

You've only created one data dictionary and used it over and over, so of course mdata contains it three times. How could it know you want three different dictionaries? Set data = {} each time to create a fresh dictionary.

Here is a visualisation of your code. Click '<< First' and then 'Forward >' a bunch of times to step through it.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89