DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Python Dictionary Methods Explained Simply (Common Operations)

Dictionaries have methods for accessing and modifying key-value pairs.

Getting values

person = {"name": "Alex", "age": 25}

print(person.get("name"))      # Alex
print(person.get("city"))      # None (no error)
print(person.get("city", "Unknown"))  # Unknown
Enter fullscreen mode Exit fullscreen mode

Adding or updating

person["city"] = "Berlin"       # Add new
person["age"] = 26              # Update existing
Enter fullscreen mode Exit fullscreen mode

Update multiple:

person.update({"job": "developer", "age": 27})
print(person)
Enter fullscreen mode Exit fullscreen mode

Removing items

age = person.pop("age")         # Removes and returns value
print(age)                      # 27

person.popitem()                # Removes last item

del person["job"]               # Delete by key

person.clear()                  # Empty dictionary
Enter fullscreen mode Exit fullscreen mode

Checking keys

print("name" in person)         # True or False
print(person.keys())            # dict_keys(['name', 'city'])
print(person.values())          # dict_values(['Alex', 'Berlin'])
print(person.items())           # dict_items([('name', 'Alex'), ...])
Enter fullscreen mode Exit fullscreen mode

Simple examples

Student grades:

grades = {"math": 90, "science": 85}
grades["english"] = 88
print(grades.get("math"))  # 90
Enter fullscreen mode Exit fullscreen mode

Config settings:

settings = {"theme": "dark"}
settings.update({"font": "large", "notifications": True})
print(settings)
Enter fullscreen mode Exit fullscreen mode

Quick summary

  • Get safely with .get().
  • Add/update with assignment or .update().
  • Remove with .pop(), .popitem(), del, .clear().
  • View with .keys(), .values(), .items().

Practice dictionary methods on data. They are essential for managing key-value information in Python programs.

Top comments (0)