Dictionaries
Dictionaries in Python are a type of collection where each element is a key-value pair. Unlike lists, which use integer indexes, dictionaries use keys as identifiers. These keys can be of any immutable type and must be unique within the dictionary. The corresponding values can be of any type, including immutable or mutable objects, and can contain duplicates.
To create a dictionary, curly brackets {} are used, with key-value pairs separated by colons :. For example:
albums = {
"Back in Black": 1980,
"The Dark Side Of The Moon": 1973,
"The Bodyguard": 1992
}
This dictionary contains album titles as keys and their release years as values.
To access a value in a dictionary, square brackets [] are used with the key. For instance:
print(albums["Back in Black"]) # Output: 1980
To add a new entry to a dictionary:
albums["Graduation"] = 2007
albums["Graduation"] = 2007
To delete an entry from a dictionary:
del albums["The Bodyguard"]
To check if a key is present in a dictionary:
print("Back in Black" in albums) # Output: True
print("Thriller" in albums) # Output: False
To retrieve all keys or values from a dictionary:
keys = albums.keys()
values = albums.values()
This provides a list-like object containing all keys or values respectively.
Dictionaries provide a powerful and flexible way to store and manipulate data in Python, offering efficient lookup and retrieval operations.
Comments
Post a Comment