-1

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?

VengaVenga
  • 680
  • 1
  • 10
  • 13
  • 1
    Hmm... can you elaborate on what is `x` and how does it fit in with your question? – TrebledJ Dec 19 '18 at 14:48
  • 2
    uh. `child['age'] += 1` works if that's what you meant. – Paritosh Singh Dec 19 '18 at 14:48
  • Relevant, though not a dupe: https://stackoverflow.com/questions/12229064/mapping-over-values-in-a-python-dictionary – chepner Dec 19 '18 at 15:02
  • Replace `x` with `child`, and the code would work, though it's still not terribly elegant. – chepner Dec 19 '18 at 15:04
  • 1
    A method like `update_map` might be nice: `child.update_map({'age': lambda x=0: x + 1, 'weight': lambda x: 20)`. Each value in the update dict is not the new value for the key, but a function to compute the new value from the old. For new keys, a default default value of `None` could be supplied to the function. Here, the `age` function will use `0` as the old age if the key isn't present, while the `weight` function would receive `None` (and ignore it). – chepner Dec 19 '18 at 15:06
  • Sorry, x should be child. chepner nailed it. Update_map would have been the solution I kind of had in my mind but overall it's a little bit overengineered. child['age'] += 1 does the job and is perfectly readable and compact. – VengaVenga Dec 19 '18 at 17:06

3 Answers3

2

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}
Zaggo
  • 73
  • 1
  • 6
0

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 
Sir1
  • 732
  • 1
  • 8
  • 18
0

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}