Here we update a dictionary:
child = {'i':0, 'name': 'Mike', 'age': 5, 'weight': 17}
child.update({'age': x['age']+1, 'weight': 20})
Any way to use an operator like age += 1 or more elegant way to do this?
Here we update a dictionary:
child = {'i':0, 'name': 'Mike', 'age': 5, 'weight': 17}
child.update({'age': x['age']+1, 'weight': 20})
Any way to use an operator like age += 1 or more elegant way to do this?
Just do child['age']+=1
:
>>> child = {'i':0, 'name': 'Mike', 'age': 5, 'weight': 17}
>>> child
{'i': 0, 'age': 5, 'name': 'Mike', 'weight': 17}
>>> child['age']+=1
>>> child
{'i': 0, 'age': 6, 'name': 'Mike', 'weight': 17}
if the dictionary already has the item with a given key you can update it using the key and new data like this:
child['age'] +=1
child['weight'] = 20
Use multiple assignment A simple feature in python that we tend to forget about.
child['age'], child['weight'] = child['age'] + 1, 20
print(child)
Output:
{'i': 0, 'name': 'Mike', 'age': 6, 'weight': 20}