0

I am new to Data Science .I am Having Problem in changing a particaular key's particular value in dictionary.I have a dictionary which represents class of iris plant each have 4 attributes sepal_length,sepal_width,petal_length and petal_width For e.g

iris-setosa={sepal_length,sepal_width,petal_length,petal_width}

iris-veriginica={sepal_length,sepal_width,petal_length,petal_width}

iris-veronica={sepal_length,sepal_width,petal_length,petal_width}

Initially i have initialized all these attributes to zero. Now i want just to change sepal_length of iris-setosa to 2 by adding 2 in it(it is mandatory to do it by addition only)

import numpy as np
import pandas as pd
dic={}
dic2={}


dic['sepal_length']=0
dic['petal_length']=0
dic['sepal_width']=0
dic['petal_width']=0
dic2['iris-setosa']=dic
dic2['iris-verginica']=dic
dic2['iris-veronica']=dic


dic2['iris-setosa']['sepal_length']=dic2['iris-setosa']['sepal_length']+2
print(dic2)

but the result come out is as :

{'iris-setosa': {'sepal_width': 0, 'petal_width': 0, 'sepal_length': 2, 'petal_length': 0}, 'iris-verginica': {'sepal_width': 0, 'petal_width': 0, 'sepal_length': 2, 'petal_length': 0}, 'iris-veronica': {'sepal_width': 0, 'petal_width': 0, 'sepal_length': 2, 'petal_length': 0}}

the above code is updating sepal_length of all i.e iris-setosa,iris-verginica and iris-veronica,Which was not required.How should i change value of sepal_length of iris-setosa only. Please ignore any grammatical mistake if i made any.

1 Answers1

1

All three entries in dic2 point to the same dictionary. So when you update it via one reference, all entries will change (since they are in fact the same dictionary). Instead, you should create a separate dictionary for each entry, e.g.:

dic={}

for name in ['iris-setosa', 'iris-verginica', 'iris-veronica']:
    entry = {'sepal_length' : 0, 'petal_length' : 0, 'sepal_width' : 0, 'petal_width' : 0}
    dic[name] = entry

dic['iris-setosa']['sepal_length'] = dic['iris-setosa']['sepal_length'] + 2
Mureinik
  • 297,002
  • 52
  • 306
  • 350