maverick9888
maverick9888

Reputation: 512

Issue with nested dictionary

Following code :

def readData():

symbolData = {'20MICRONS':{'CLOSEPRICE':0}}
    
dateWiseStockData = {'20210318': symbolData, '20210319':symbolData}

dates = ['20210318', '20210319']

print(dateWiseStockData)

i = 17

for analysisDate in dates:

    print(analysisDate)

    dateWiseStockData[analysisDate]['20MICRONS']['CLOSEPRICE'] = i
    
    i += 1

print(dateWiseStockData)
readData()

Shows following output :

{'20210318': {'20MICRONS': {'CLOSEPRICE': 0}}, '20210319': {'20MICRONS': {'CLOSEPRICE': 0}}}
20210318
20210319
{'20210318': {'20MICRONS': {'CLOSEPRICE': 18}}, '20210319': {'20MICRONS': {'CLOSEPRICE': 18}}}

Shouldn't this output be :

{'20210318': {'20MICRONS': {'CLOSEPRICE': 0}}, '20210319': {'20MICRONS': {'CLOSEPRICE': 0}}}
20210318
20210319
{'20210318': {'20MICRONS': {'CLOSEPRICE': 17}}, '20210319': {'20MICRONS': {'CLOSEPRICE': 18}}}

I tried everything but can't get this working. Is my understanding of nested dictionaries incorrect here ?

Upvotes: 0

Views: 115

Answers (1)

buran
buran

Reputation: 14233

When you do

dateWiseStockData = {'20210318': symbolData, '20210319':symbolData}

it's the same dict as value for both keys. I.e. that is the same object, with same id. dicts are mutable so when you change one of them in the loop, you actually change both.

symbolData = {'20MICRONS':{'CLOSEPRICE':0}}  
dateWiseStockData = {'20210318': symbolData, '20210319':symbolData}
for key, value in dateWiseStockData.items():
    print(f'{key}:{value}: value id:{id(value)}')

output

20210318:{'20MICRONS': {'CLOSEPRICE': 0}}: value id:139895906910640
20210319:{'20MICRONS': {'CLOSEPRICE': 0}}: value id:139895906910640

One way to do what you want:

def readData():
    dates = ['20210318', '20210319']
    dateWiseStockData = {}
    print(dateWiseStockData)
    i = 17
    for analysisDate in dates:
        dateWiseStockData[analysisDate] = {'20MICRONS':{'CLOSEPRICE':i}}
        i += 1
        print(dateWiseStockData)
readData()

output

{}
{'20210318': {'20MICRONS': {'CLOSEPRICE': 17}}}
{'20210318': {'20MICRONS': {'CLOSEPRICE': 17}}, '20210319': {'20MICRONS': {'CLOSEPRICE': 18}}}

Upvotes: 2

Related Questions