Skip to main content

Dictionaries

Dictionaries in Python allow you to store key-value pairs, which is useful for representing objects or collections of data with a relationship.

MethodBrief descriptionSmall descriptive example
get()Returns the value associated with a key.Gets the price of the product with key "apple".
keys()Returns a view with all the keys of the dictionary.Lists all keys like "name", "age".
values()Returns a view with all the values of the dictionary.Lists all values like "Anna", 25.
items()Returns a view with (key, value) pairs from the dictionary.Iterates over key and value in a for loop.
pop()Removes a key and returns its associated value.Removes the "user" key and returns its content.
popitem()Removes the last inserted key-value pair (in modern Python versions).Removes the last added item.
update()Adds or updates key-value pairs from another dictionary or parameters.Adds "city": "Bogota" to the user dictionary.
clear()Removes all elements from the dictionary.Completely empties the configuration dictionary.
copy()Returns a shallow copy of the dictionary.Creates a copy of the user profile dictionary.
setdefault()Returns the value of a key; if it does not exist, adds it with a default value.Ensures "email" exists, otherwise assigns it None.