Register to get access to free programming courses with interactive exercises

Changing data in the dictionary Python: Dictionaries and Sets

Python dictionaries are mutable. If we want to add a new key-value pair, we do not need the .append or other separate list methods. Usual assigning is enough:

d = {}  # An empty dictionary
d["a"] = 100
print(d)  # => {'a': 100}
d["b"] = 200
d["a"] = 0
print(d)  # => {'a': 0, 'b': 200}

Here you can see that assigning a value to a new key looks the same as setting values to existing keys — it is convenient. Removing items from the dictionary is done using the pop method. The dictionary is already more like a list in this case. Only we use the key instead of the index:

d = {'a': 1, 'b': 2}
d.pop('a')  # 1
d  # {'b': 2}
d.pop('BANG')  # KeyError: 'BANG'

The example shows that Python will throw an exception if you try to extract a value from a non-existent key. However, we can call the pop method with a default value. In this case, if there is no key in the dictionary, we will get this value with no exception thrown:

d = {'a': 1, 'b': 2}
d.pop('BANG', None)
d.pop('BANG', 42)  # 42

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs
profession
new
Developing web applications with Django
10 months
from scratch
under development
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.