Python Dictionary contains List as Value – How to update?
Question:
I have a dictionary which has value as a list.
dictionary = {
'C1' : [10,20,30]
'C2' : [20,30,40]
}
Let’s say I want to increment all the values in list of C1 by 10, how do I do it?
dictionary.get('C1')
gives me the list but how do i update it?
Answers:
Probably something like this:
original_list = dictionary.get('C1')
new_list = []
for item in original_list:
new_list.append(item+10)
dictionary['C1'] = new_list
dictionary["C1"]=map(lambda x:x+10,dictionary["C1"])
Should do it…
>>> dictionary = {'C1' : [10,20,30],'C2' : [20,30,40]}
>>> dictionary['C1'] = [x+1 for x in dictionary['C1']]
>>> dictionary
{'C2': [20, 30, 40], 'C1': [11, 21, 31]}
An accessed dictionary value (a list in this case) is the original value, separate from the dictionary which is used to access it. You would increment the values in the list the same way whether it’s in a dictionary or not:
l = dictionary.get('C1')
for i in range(len(l)):
l[i] += 10
why not just skip .get altogether and do something like this?:
for x in range(len(dictionary["C1"]))
dictionary["C1"][x] += 10
for i,j in dictionary .items():
if i=='C1':
c=[]
for k in j:
j=k+10
c.append(j)
dictionary .update({i:c})
I have a dictionary which has value as a list.
dictionary = {
'C1' : [10,20,30]
'C2' : [20,30,40]
}
Let’s say I want to increment all the values in list of C1 by 10, how do I do it?
dictionary.get('C1')
gives me the list but how do i update it?
Probably something like this:
original_list = dictionary.get('C1')
new_list = []
for item in original_list:
new_list.append(item+10)
dictionary['C1'] = new_list
dictionary["C1"]=map(lambda x:x+10,dictionary["C1"])
Should do it…
>>> dictionary = {'C1' : [10,20,30],'C2' : [20,30,40]}
>>> dictionary['C1'] = [x+1 for x in dictionary['C1']]
>>> dictionary
{'C2': [20, 30, 40], 'C1': [11, 21, 31]}
An accessed dictionary value (a list in this case) is the original value, separate from the dictionary which is used to access it. You would increment the values in the list the same way whether it’s in a dictionary or not:
l = dictionary.get('C1')
for i in range(len(l)):
l[i] += 10
why not just skip .get altogether and do something like this?:
for x in range(len(dictionary["C1"]))
dictionary["C1"][x] += 10
for i,j in dictionary .items():
if i=='C1':
c=[]
for k in j:
j=k+10
c.append(j)
dictionary .update({i:c})