Пропустить до содержимого

Как использовать python dictionary cheat sheet?

[

Python Dictionary Cheat Sheet

Introduction

Python dictionaries are an essential data structure in Python programming. They allow you to store and retrieve data in the form of key-value pairs. In this tutorial, we will provide a comprehensive cheat sheet to help you understand and utilize dictionaries in Python effectively.

Creating a Dictionary

To create a dictionary in Python, you can use the following syntax:

my_dict = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}

Accessing Dictionary Items

To access an item in a dictionary, you can use the key associated with that item. For example:

my_dict = {
"name": "John",
"age": 25,
"country": "USA"
}
print(my_dict["name"]) # Output: John

Modifying Dictionary Items

To modify an item in a dictionary, you can simply assign a new value to its key. For example:

my_dict = {
"name": "John",
"age": 25,
"country": "USA"
}
my_dict["age"] = 26
print(my_dict) # Output: {'name': 'John', 'age': 26, 'country': 'USA'}

Dictionary Methods

Python provides several methods to perform various operations on dictionaries. Some commonly used methods include:

  • get(key): Returns the value associated with a specified key. If the key does not exist, it returns None.
  • keys(): Returns a list of all the keys in the dictionary.
  • values(): Returns a list of all the values in the dictionary.
  • items(): Returns a list of all key-value pairs in the dictionary.

Let’s look at an example:

my_dict = {
"name": "John",
"age": 25,
"country": "USA"
}
print(my_dict.get("name")) # Output: John
print(my_dict.keys()) # Output: ['name', 'age', 'country']
print(my_dict.values()) # Output: ['John', 25, 'USA']
print(my_dict.items()) # Output: [('name', 'John'), ('age', 25), ('country', 'USA')]

Adding and Removing Items

To add a new item to a dictionary, you can simply assign a value to a new key. To remove an item, you can use the del keyword. Let’s see an example:

my_dict = {
"name": "John",
"age": 25,
"country": "USA"
}
my_dict["city"] = "New York"
print(my_dict) # Output: {'name': 'John', 'age': 25, 'country': 'USA', 'city': 'New York'}
del my_dict["age"]
print(my_dict) # Output: {'name': 'John', 'country': 'USA', 'city': 'New York'}

Looping through a Dictionary

You can iterate over a dictionary using a for loop to access each key-value pair. For example:

my_dict = {
"name": "John",
"age": 25,
"country": "USA"
}
for key, value in my_dict.items():
print(key, value)

Output:

name John
age 25
country USA

Conclusion

Python dictionaries are versatile data structures that allow you to store data in key-value pairs. In this cheat sheet, we covered the basics of dictionary creation, access, modification, and various methods to work with dictionaries in Python. With the help of sample codes provided, you should be well-equipped to use dictionaries effectively in your Python programs.