Python Creating Dictionary
Creating a Dictionary in Python
In Python, a dictionary is a mutable container model used to store objects of any type. Its elements are key-value pairs. Dictionaries are defined using curly braces {}. Each element consists of a key and a value, separated by a colon (:). Different key-value pairs are separated by a comma (,).
For example, we can use a dictionary to represent a student’s information:
student = {'name': '张三', 'age': 18, 'gender': '男', 'score': {'math': 90, 'chinese': 95, 'english': 85}}
The above code defines a dictionary named student, which contains four key-value pairs:
- The key is name, the value is ‘张三’
- The key is age, the value is 18
- The key is gender, the value is ‘男’
- The key is score, whose value is a nested dictionary representing the student’s grades in each subject.
Creating an Empty Dictionary
If we want to create an empty dictionary, we can use the following method:
empty_dict = {}
Or we can use the dict() function to create one:
empty_dict = dict()
Adding Elements
We can access elements in a dictionary using a key. If the key does not exist, a KeyError exception will be raised.
Now, let’s see how to add new elements to a dictionary. We can achieve this as follows:
# Define an empty dictionary
person = {}
# Add an element to the dictionary
person[‘name’] = ‘张三’
person[‘age’] = 18
person[‘gender’] = ‘男’
print(person) # Output: {‘name’: ‘张三’, ‘age’: 18, ‘gender’: ‘男’}
The above code defines an empty dictionary, person, and adds three key-value pairs to it.
Modifying Elements
If we need to modify an element in a dictionary, we can do so by specifying its key name. For example, the following code changes the age value in the person dictionary to 20:
person['age'] = 20
print(person) # Output: {'name': '张三', 'age': 20, 'gender': '男'}
Deleting Elements
We can use the del or pop methods to delete elements from a dictionary.
Use the del method to delete a key-value pair based on the key name:
# Define a dictionary
person = {'name': '张三', 'age': 18, 'gender': '男'}
# Delete the key-value pair with the gender key
del person['gender']
print(person) # Output: {'name': '张三', 'age': 18}
Use the pop method to delete a key-value pair and return the value corresponding to the key:
person = {'name': '张三', 'age': 18, 'gender': '男'}
gender_value = person.pop('gender')
print(person) # Output: {'name': 'Zhang San', 'age': 18}
print(gender_value) # Output: Male
Accessing Elements
We can access elements in a dictionary using a specified key. If the key does not exist, a KeyError exception will be thrown.
# Define a dictionary
person = {'name': 'Zhang San', 'age': 18, 'gender': 'Male'}
# Accessing Elements in a Dictionary
print(person['name']) # Output: Zhang San
print(person['age']) # Output: 18
print(person['gender']) # Output: Male
You can also use the get method to access elements in a dictionary. Unlike using brackets, if the key does not exist, an exception is not thrown. Instead, None or the specified default value is returned.
person = {'name': '张三', 'age': 18, 'gender': '男'}
# Accessing an element in a dictionary
print(person.get('name')) # Output: Zhang San
print(person.get('score')) # Output: None
The get method can also specify a default value. If the key does not exist, the specified default value is returned.
```python
person = {'name': '张三', 'age': 18, 'gender': '男'}
# Accessing an element in a dictionary
print(person.get('name', 'Default value')) # Output: 张三
print(person.get('score', 'Default value')) # Output: Default value
Traversing a dictionary
We can iterate over all elements in a dictionary using a loop.
person = {'name': '张三', 'age': 18, 'gender': '男'}
# Iterate over the keys in the dictionary
for key in person:
print(key)
# Iterate over the values in the dictionary
for value in person.values():
print(value)
# Iterate over the key-value pairs in the dictionary
for key, value in person.items():
print(key, value)
Running the above code prints the keys, values, and key-value pairs in the dictionary, in order.
Dictionary Methods
Python provides many useful dictionary methods, as shown below:
clear Method
Clears all elements in a dictionary.
person = {'name': '张三', 'age': 18, 'gender': '男'}
person.clear()
copy Method
Copies a dictionary.
person = {'name': '张三', 'age': 18, 'gender': '男'}
person_copy = person.copy()
fromkeys Method
Creates a new dictionary where the values corresponding to the specified keys are default values.
keys = ['name', 'age', 'gender']
person = dict.fromkeys(keys, 'default value')
The above code creates a dictionary named person with three keys: name, age, and gender, each with its own default value.
setdefault Method
Gets the value corresponding to a specified key. If the key does not exist, sets its key-value pair and returns the default value.
person = {'name': '张三', 'age': 18, 'gender': '男'}
name_value = person.setdefault('name', '无名氏')
score_value = person.setdefault('score', {'math': 90, 'chinese': 95, 'english': 85})
print(name_value) # Output: 张三
print(score_value) # Output: {'math': 90, 'chinese': 95, 'english': 85}
The above code uses the setdefault method to retrieve the values corresponding to the existing key ‘name’ and the non-existent key ‘score’, and then sets the key-value pair.
update method
Used to update elements in a dictionary.
person = {'name': '张三', 'age': 18, 'gender': '男'}
person_update = {'age': 20, 'score': {'math': 90, 'chinese': 95, 'english': 85}}
person.update(person_update)
print(person) # Output: {'name': '张三', 'age': 20, 'gender': '男', 'score': {'math': 90, 'chinese': 95, 'english': 85}}
The above code uses the update method to update the element in the dictionary person, changing the value corresponding to the key ‘age’ from 18 to 20, and added a key-value pair, where the key is ‘score’ and the value is a dictionary.
Conclusion
Dictionaries in Python are very practical data structures. They can be used to store objects of any type and provide a rich set of operations. Dictionaries are frequently used in daily development. Mastering dictionary usage is crucial for improving development efficiency and code quality.