In Python, a dictionary consists of a series of key-value pairs, where each key has a corresponding value. Unlike lists, the elements of a dictionary do not have a fixed order and can be quickly accessed by their keys.
1. Basic Operations on Dictionaries
Creating a dictionary is very simple:
# Create an empty dictionaryempty_dict = {}# Dictionary with initial key-value pairsuser = { 'name': 'Alice', 'age': 30, 'city': 'New York'}
For an existing dictionary, we can perform the following basic operations:
1. Viewing:
user['name']# This can also be done asuser.get('name')
Output:
'Alice'
2. Adding key-value pairs:
user['edu'] = 'Peking University'# This can also be done asuser.update({'edu':'Peking University','Nation':'China'})
3. Modifying values (keys cannot be modified):
user['age'] = 31# This can also be done asuser.update({'age':31})
Careful readers may have noticed that update can add multiple elements and also update existing elements’ values.4. Deleting key-value pairs:
del user['edu']# This can also be done asuser.pop('Nation')
2. Iterating Over Dictionaries
During data analysis, we often need to process all keys or values in a dictionary:1. Iterating over key-value pairs:
for k,v in user.items(): print(k,v)
Output:
name Aliceage 30city New York
The above shows how to process key-value pairs together; sometimes we need to process keys and values separately, as follows:2. Iterating over keys:
for k in user.keys(): print(k)
Output:
nameagecity
3. Iterating over values:
for v in user.values(): print(v)
Output:
Alice30New York
3. Dictionary Error Handling
Accessing a non-existent key in a dictionary will raise an error.
user['office']
Output:
Traceback (most recent call last): File "<stdin>", line 1, in <module>KeyError: 'office'
Solution: Add the target as a new key-value pair.
user.setdefault('office','1025')
Output:
'1025'
At this point, the dictionary now has an ‘office’ key. In fact, the setdefault method is similar to the get method, both are used to retrieve a key’s value. The difference is that get does not raise an error for non-existent keys and does not return any value (which is not beneficial for program development analysis). The setdefault method, however, will add the target key as a new key if it does not exist.
{'name': 'Alice', 'age': 30, 'city': 'New York', 'office': '1025'}
4. Merging Dictionaries
If there are multiple dictionaries to merge, you can use the “|” symbol.
dict0={1:'a',2:'b'}dict1={1:'c',3:'d'}print(dict0|dict1)
Output:
{1: 'c', 2: 'b', 3: 'd'}
Note that using the “|” symbol to merge does not change the original dictionaries but generates a new dictionary.
5. Conclusion
Dictionaries are one of the most commonly used data structures in Python. In data analysis work, we often need to store key-value data, such as the relationship between user IDs and names, product pricing information, etc. In summary, dictionaries provide a quick solution and are frequently used by those who work with pandas.
———Knowledge needs to be shared and disseminated———
This is thePythonKnowledge Station, dedicated to knowledge dissemination, allowing more people to understandPython, usePython, and lovePython. If you are a programmer, amateur developer,ITpractitioner, or anyone interested inPython, you can joinPythonKnowledge Station, and let us enjoy the ocean of knowledge together.———Follow me for more knowledge———