How would I add to an integer within a dict?

Question:

test = {"poop":{"okay":[10]}}
print(test)

For example, I want the 10 within["okay"], to now be 20.

Asked By: Br3xin

||

Answers:

Hope this helps:

# To update the value in the list
test["poop"]["okay"][0] = 20

# Replaces the list altogether
test["poop"]["okay"] = 20
Answered By: PCDSandwichMan

You just need to use square brackets to perform a look up on each level, then once you’re at the 10 you can update it.

>>> test = {"poop":{"okay":[10]}}
>>> test
{'poop': {'okay': [10]}}

>>> test['poop']
{'okay': [10]}

>>> test['poop']['okay']
[10] # note that this is a list w/ 1 element

>>> test['poop']['okay'][0]
10

# put it all together, let's add 10 to the value
>>> test['poop']['okay'][0] += 10
>>> test
{'poop': {'okay': [20]}}

Answered By: Cameron Riddell
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.