Reputation: 35
If I have a dictionary like so:
d = {'USA' : [0,0,0], 'CAN' : [0,0,0]}
How can I update a specific element in the value?
My goal is to update it to look like (for example) this:
d = {'USA' : [0,1,0], 'CAN' : [1,0,0]}
I was thinking something like
d['USA'] = d.get('USA')[1] + 1
d['CAN'] = d.get('CAN')[0] + 1
but this doesn't seem to work. Any suggestions? I hope this is clear.
Upvotes: 1
Views: 82
Reputation: 516
The simplest way would be to just say
d['USA'][1] += 1
That will get you the updated list.
Upvotes: 1
Reputation: 16188
Do
d['USA'][1]=d['USA'][1]+1
d['CAN'][0]=d['USA'][0]+1
In your example you were replacing the whole list with a single number.
Upvotes: 0
Reputation: 1121446
You have lists inside of your dictionary, so the d[key]
part of the expression returns a list. Just keep adding [..]
indexings:
d['USA'][1] += 1
d['CAN'][0] += 1
You could break it down with intermediary variables if that is easier:
sublist = d['USA']
sublist[1] += 1
sublist = d['CAN']
sublist[0] += 1
Upvotes: 4