Python dict loses 1st entry

Viewed 36

For some reason variable1 just disappears. So the following code gives a KeyError. Variable2 can be accessed as normal. Why?

testdict = {"variable1": 17}
testdict = {"variable2": 5}
print(testdict["variable1"])
1 Answers

You're looking for update.

testdict = {"variable1": 17}
testdict.update({"variable2": 5})
print(testdict)

EDIT: As mentioned in the comments, creating and updating a dictionary with just two key-value pairs is pretty wasteful.

you can use

testdict = {"variable1": 17, "variable2": 5}

instead

Related