Dictionaries in Python
A dictionary in Python is a collection of key-value pairs. Each key-value pair maps the key to its associated value. Dictionaries are mutable, meaning they can be changed.
You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces {}. A colon : separates each key from its associated value.
Try this code:
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
output:
In this example, "name", "age", and "city" are the keys, and "Alice", 25, and "New York" are the corresponding values.
Example:
Accessing Values in a Dictionary
Try this Code:
print(person["name"]) # prints "Alice"
Example:
If you try to access a key that does not exist in the dictionary, Python will raise an error. To avoid this, you can use the get() method, which returns None if the key is not in the dictionary:
print(person.get("job")) # prints "None"
Adding and Modifying Key-Value Pairs
Example:
person["job"] = "Engineer"
print(person)
prints "{'name': 'Alice', 'age': 25, 'city': 'New York', 'job': 'Engineer'}"
You can also modify the value associated with a key:
Example:
person["age"] = 26
print(person)
prints "{'name': 'Alice', 'age': 26, 'city': 'New York', 'job': 'Engineer'}"
Removing Key-Value Pairs:-
You can remove a key-value pair using the del keyword:
Example:
del person["age"]
print(person)
prints "{'name': 'Alice', 'city': 'New York', 'job': 'Engineer'}"
Iterating Over a Dictionary:
You can iterate over a dictionary using a for loop. This will iterate over the keys in the dictionary:
Example:
for key in person:
print(key) # prints "name", "city", and "job" in some order
To iterate over the values in a dictionary, you can use the values() method:
for value in person.values():
Example
print(value) # prints "Alice", "New York", and "Engineer" in some order
To iterate over the key-value pairs in a dictionary, you can use the items() method:
Example
for key, value in person.items():
print(f"{key}: {value}")
prints "name: Alice", "city: New York", and "job: Engineer" in some order
Checking if a Key Exists
Example:
if "name" in person:
print("Name is in the dictionary.") # prints "Name is in the dictionary."
You can also use the keys() method to achieve the same result:
Example:
if "name" in person.keys():
print("Name is in the dictionary.") # prints "Name is in the dictionary."
Checking if a Value Exists
You can check if a value exists in a dictionary:
Example:
if "Engineer" in person.values():
print("Engineer is in the dictionary.") # prints "Engineer is in the dictionary."
Dictionary Comprehension
Just like list comprehension, dictionary comprehension is an elegant and concise way to create a new dictionary from an iterable in Python:
Example:
squares = {x: x*x for x in range(6)}
print(squares) # prints "{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}"
Importance of Knowing this Topic:
Dictionaries are a fundamental data structure in Python and are widely used in various types of programming, including web development, data analysis, AI, etc,...
Tags:
Data Structures
Python Dictionary
Key-Value Pairs
Mutable Types
Python Built-in Types
Dictionary Methods
Dictionary Access
Dictionary Update
Dictionary Iteration
Dictionary Comprehension
Nesta página do site você pode assistir ao vídeo on-line What is Dictionary in Python - Complete Tutorial for Beginners duração online em boa qualidade , que foi baixado pelo usuário Pycent com 03 Agosto 2023, compartilhe o link com seus amigos e conhecidos, no youtube este vídeo já foi visto 20 vezes e gostou 1 espectadores. Boa visualização!