3.1 Displaying Child Elements
As you already know, a dictionary internally stores pairs of key-value elements. It has methods that let us access these data: keys()
, values()
, and items()
. I'm going to dive deeper into these below.
Important!
These methods don't just return simple lists of elements, but what are called views
. Dictionary views provide a dynamic view of keys, values, and key-value pairs contained in the dictionary. These views automatically update when the dictionary changes.
Method keys()
The keys()
method returns a view of all the keys in the dictionary. The result is a dict_keys
object, which supports iteration and other operations similar to sets.
person = {"name": "Alice", "age": 25, "city": "New York"}
keys = person.keys()
print(keys) # dict_keys(['name', 'age', 'city'])
Iterating over keys
for key in person.keys():
print(key)
# Output:
# name
# age
# city
Method values()
The values()
method returns a view of all the values in the dictionary. The result is a dict_values
object, which also supports iteration.
person = {"name": "Alice", "age": 25, "city": "New York"}
values = person.values()
print(values) # dict_values(['Alice', 25, 'New York'])
Iterating over values
for value in person.values():
print(value)
# Output:
# Alice
# 25
# New York
Method items()
The items()
method returns a view of all the key-value pairs in the dictionary. The result is a dict_items
object, which supports for-loop operations.
person = {"name": "Alice", "age": 25, "city": "New York"}
items = person.items()
print(items) # dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])
Iterating over key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
# Output:
# name: Alice
# age: 25
# city: New York
3.2 Dynamic Updates
One of the important properties of dictionary views is their dynamic updating. This means that if the dictionary changes, the views automatically reflect these changes.
person = {"name": "Alice", "age": 25}
keys = person.keys()
print(keys) # dict_keys(['name', 'age'])
# Adding a new element
person["city"] = "New York"
print(keys) # dict_keys(['name', 'age', 'city'])
Converting Views to Other Collections
Dictionary views can be converted to other collections like lists, sets, or tuples for additional operations.
person = {"name": "Alice", "age": 25, "city": "New York"}
# Converting keys() to a list
keys_list = list(person.keys())
print(keys_list) # ['name', 'age', 'city']
# Converting values() to a set
values_set = set(person.values())
print(values_set) # {'Alice', 25, 'New York'}
# Converting items() to a list of tuples
items_list = list(person.items())
print(items_list) # [('name', 'Alice'), ('age', 25), ('city', 'New York')]
GO TO FULL VERSION