Python辞書チートシート:使い方を簡単に説明
Python Dictionary Cheat Sheet
Creating a Dictionary
To create a dictionary in Python, you can use the curly brackets ”{ }” and separate key-value pairs with a colon ”:“. Here’s an example:
You can also use the dict()
constructor to create a dictionary. For example:
Accessing Dictionary Values
To access values in a dictionary, you can use the square brackets ”[ ]” and provide the corresponding key. Here’s an example:
Modifying Dictionary Values
You can modify the values of a dictionary by assigning a new value to a specific key. Here’s an example:
Dictionary Methods
Python provides various methods to perform operations on dictionaries. Here are some commonly used methods:
Method | Description |
---|---|
keys() | Returns a list of all keys in the dictionary. |
values() | Returns a list of all values in the dictionary. |
items() | Returns a list of key-value pairs in the dictionary. |
get(key, default) | Returns the value for the given key. If the key does not exist, it returns the default value. |
pop(key) | Removes the key-value pair for the given key and returns the value. |
update(other_dict) | Updates the dictionary with the key-value pairs from the other dictionary. |
clear() | Removes all key-value pairs from the dictionary. |
len() | Returns the number of key-value pairs in the dictionary. |
Here’s an example showing the usage of these methods:
Iterating Over Dictionary
You can iterate over a dictionary using a for
loop. By default, the loop iterates over the keys of the dictionary. Here’s an example:
Checking if a Key Exists
You can check if a specific key exists in a dictionary using the in
keyword. Here’s an example:
These are some basic operations you can perform with dictionaries in Python. By understanding the key concepts and utilizing the available methods, you can efficiently work with dictionaries to store and retrieve data in your Python programs.