2.1 Getting the Number of Elements
In Python, to get the number of elements in a dictionary, you use the built-in len()
function. This function returns the number of key-value pairs in the dictionary. Or just the number of keys, if you prefer.
Example of using the function:
person = {"name": "Alice", "age": 25, "city": "New York"}
num_elements = len(person)
print(num_elements) # Output: 3
In this example, we have a dictionary person
with three elements. The function len(person)
returns the number of elements in the dictionary, which is 3.
Checking if a Dictionary is Empty
You can use the len()
function to check if a dictionary is empty. This is useful in conditions and loops.
empty_dict = {}
print(len(empty_dict)) # Output: 0
person = {"name": "Alice", "age": 25, "city": "New York"}
if len(person) > 0:
print("The dictionary is not empty")
else:
print("The dictionary is empty")
Dictionary with Nested Structures
The len()
function only counts the number of top-level keys, regardless of what is contained as values.
complex_dict = {
name: "Alice",
details: {
age: 25,
city: "New York"
},
hobbies: ["reading", "traveling"]
}
print(len(complex_dict)) # Output: 3
In this example, we have a dictionary with nested data structures. len(complex_dict)
returns 3 because there are three top-level keys: "name", "details", and "hobbies".
len()
ignores keys inside nested data structures, like "age" and "city" inside the "details" dictionary, because len()
only counts top-level keys. If you need to count all elements, including nested structures, you would need to use a recursive method. But not today.
2.2 Determining the Type
The type()
function in Python is used to determine the type of an object. When working with dictionaries, type()
helps you find out if an object is an instance of the dict
class. This can be useful in various scenarios, like checking data types before performing operations on a dictionary.
Examples of usage:
Checking the Type of an Object
person = {"name": "Alice", "age": 25, "city": "New York"}
print(type(person)) # Output: <class 'dict'>
In this example, we create a dictionary person
and use type
to determine its type. The function returns <class 'dict'>
, indicating that person
is a dictionary.
Conditional Check of Data Type
The type()
function can be used to check the data type in conditional statements, allowing you to perform certain operations only for objects of type dict
.
data = {"name": "Alice", "age": 25, "city": "New York"}
if type(data) is dict:
print("This is a dictionary.")
else:
print("This is not a dictionary.")
In this example, the conditional statement checks if data
is a dictionary and executes the appropriate code.
The type()
function can be used inside custom functions to check the type of arguments, ensuring the function handles the correct data type.
Example:
def process_data(data):
if type(data) is dict:
print("Processing dictionary...")
# Perform operations on the dictionary
else:
print("Error: Expected a dictionary.")
data = {"name": "Alice", "age": 25, "city": "New York"}
process_data(data)
In this example, the process_data
function checks if the argument data
is a dictionary and performs the appropriate operations only for dictionaries.
2.3 Accessing an Element
Working with dictionary elements is similar to working with lists or tuples—we also use square brackets. However, instead of the index of the element in the brackets, you specify the key. A dictionary key can be any immutable item: a string, number, or even a tuple.
dictionary[key]
Example:
person = {"name": "Alice", "age": 25, "city": "New York"}
name = person["name"]
print(name) # Output: Alice
If the key is missing, an error will occur:
person = {"name": "Alice", "age": 25, "city": "New York"}
person["country"] # will raise KeyError: 'country'
The get(key, def_value)
method
The get()
method allows you to safely obtain a value by its key. If the key is missing, the method returns a default value (None
, if no default value is specified). This prevents a KeyError
from being raised.
person = {"name": "Alice", "age": 25, "city": "New York"}
age = person.get("age")
print(age) # Output: 25
country = person.get("country", "USA")
print(country) # Output: USA
You can pass a value as the second parameter to the get()
method to return if the desired key is not present in the dictionary.
The setdefault()
method works similarly to the get()
method, but if the key is not present in the dictionary, the method not only returns the default value but also adds a new pair key: value
to the dictionary.
person = {"name": "Alice", "age": 25}
city = person.setdefault("city", "New York")
print(city) # Output: New York
print(person) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
GO TO FULL VERSION