Home > front end >  How to add a new element in python LIST/DICT?
How to add a new element in python LIST/DICT?

Time:06-08

data={
  'a':{'no':'1','lang':['uno','one']},
  'b':{'no':'2','lang':['due','two']},
  'c':{'no':'3','lang':['tre','three']}
}
print(data) #OK
print(data['a']['lang'][0]) #OK
data['d']['no']='4' #ERROR
data['d']['lang'][0]='quattro' #ERROR
data['d']['lang'][1]='four' #ERROR
print(data)

I would add a new element with a new master index 'd' with contents:

{'d':{'no':'4','lang':['quattro','four']}

But I got an error on script for adding a new data element assignment below

.......
data['d']['no']='4' #ERROR
data['d']['lang'][0]='quattro' #ERROR
data['d']['lang'][1]='four' #ERROR
.......

CodePudding user response:

data={
    'a':{'no':'1','lang':['uno','one']},
    'b':{'no':'2','lang':['due','two']},
    'c':{'no':'3','lang':['tre','three']}
}
data['d']={'no':'4','lang':['quattro','four']}
print(data)

CodePudding user response:

you are getting this error since you try to change a dictionary that does not exist, your code would make sense if 'data['d']' were a dictionary but it doesn't exists yet, try adding a new dictionary in the same format to 'data['d']' and that should fix your problem :)

data={
  'a':{'no':'1','lang':['uno','one']},
  'b':{'no':'2','lang':['due','two']},
  'c':{'no':'3','lang':['tre','three']}
}
print(data) #OK
print(data['a']['lang'][0]) #OK

data['d'] = {'no':'4','lang':['tre','three']} # the row i added 

data['d']['lang'][0]='quattro' #works now
print(data)

output:

{'a': {'no': '1', 'lang': ['uno', 'one']}, 'b': {'no': '2', 'lang': ['due', 'two']}, 'c': {'no': '3', 'lang': ['tre', 'three']}, 'd': {'no': '4', 'lang': ['quattro', 'three']}}
  • Related