Dictonary & Build Methods
Dictonary & Build Methods
Dictionaries are
mutable, unordered, and indexed by keys, which are unique and can be of any hashable type
(typically strings or numbers). The values associated with keys can be of any type.
Creating a Dictionary
we can create a dictionary by using curly braces {} or by using the dict() constructor.
person = {
"name": "John",
"age": 30,
To access values in a dictionary, we use the key inside square brackets [] or the .get() method.
# Accessing with the get() method (prevents KeyError if key doesn't exist)
print(person.get("age")) # Output: 30
person["gender"] = "Male"
person["age"] = 31
Removing Elements
pop(key) removes the item with the specified key and returns its value.
popitem() removes and returns the last inserted item (useful for Python 3.7+ where
dictionaries preserve insertion order).
print(age) # Output: 31
del person["city"]
print(key)
print(value)
print(f"{key}: {value}")
Dictionary Methods
Python dictionaries are powerful and flexible, allowing you to store and manipulate data efficiently
using key-value pairs. Common operations include accessing, adding, updating, and removing
elements, as well as looping through the dictionary.
Python dictionaries come with a variety of built-in methods to manipulate and interact with the data
they store. Below is a list of commonly used dictionary methods in Python, along with examples for
each.
1. dict.clear()
person.clear()
print(person) # Output: {}
2. dict.copy()
person_copy = person.copy()
3. dict.get(key[, default])
Returns the value for the specified key. If the key does not exist, returns the optional default value
(or None if no default is provided).
print(person.get("age")) # Output: 30
4. dict.items()
Returns a view object that displays a list of dictionary's key-value tuple pairs.
5. dict.keys()
Returns a view object that displays a list of all the dictionary’s keys.
person = {"name": "John", "age": 30}
6. dict.values()
Returns a view object that displays a list of all the dictionary’s values.
7. dict.pop(key[, default])
Removes and returns the value for the specified key. If the key is not found, it returns the optional
default value (or raises a KeyError if no default is provided).
age = person.pop("age")
print(age) # Output: 30
9. dict.setdefault(key[, default])
If the key exists, it returns its value. If the key doesn’t exist, it inserts the key with the provided
default value and returns the default.
print(age) # Output: 25
10. dict.update([other])
Updates the dictionary with elements from another dictionary or iterable of key-value pairs. Existing
keys will be updated, and new ones will be added.
Creates a new dictionary from the given sequence of keys, with all values set to the specified value
(or None if no value is provided).