Simple Python Guide For Beginners
Working with Dictionaries
In this section, you will learn about dictionaries in Python. Dictionaries are unordered collections of key-value pairs. We will cover topics such as creating dictionaries, accessing values in a dictionary, dictionary methods (keys, values, items), modifying dictionaries, dictionary comprehension, and nested dictionaries.
Creating Dictionaries
In Python, you can create dictionaries by enclosing key-value pairs in curly braces {}. Here are some examples:
person = {
"name": "John",
"age": 25,
"city": "New York"
}
car = dict(make="Toyota", model="Camry", year=2020)
Accessing Values in a Dictionary
You can access values in a dictionary by providing the corresponding key. Here’s an example:
person = {
"name": "John",
"age": 25,
"city": "New York"
}
print(person["name"]) # Output: John
print(person["age"]) # Output: 25
Dictionary Methods
Python provides several built-in methods that can be used with dictionaries. Here are a few commonly used dictionary methods:
person = {
"name": "John",
"age": 25,
"city": "New York"
}
keys = person.keys() # Get the keys
values = person.values() # Get the values
items = person.items() # Get the key-value pairs
print(keys) # Output: dict_keys(['name', 'age', 'city'])
print(values) # Output: dict_values(['John', 25, 'New York'])
print(items) # Output: dict_items([('name', 'John'), ('age', 25), ('city', 'New York')])
Modifying Dictionaries
You can modify dictionaries by assigning new values to existing keys or adding new key-value pairs. Here’s an example:
person = {
"name": "John",
"age": 25,
"city": "New York"
}
person["age"] = 26 # Update value
person["country"] = "USA" # Add new key-value pair
print(person) # Output: {'name': 'John', 'age': 26, 'city': 'New York', 'country': 'USA'}