文章目录
Dictionaries - Working with Key-Value Pairs
/*
- File: dictionaries.md
- Project: 4_dictionaries
- File Created: Friday, 10th March 2023 10:26:31 pm
- Author: Hanlin Gu (hg_fine_codes@163.com)
- Last Modified: Saturday, 11th March 2023 4:38:07 pm
- Modified By: Hanlin Gu (hg_fine_codes@163.com>)
*/
1. Dictionary definition
Each word that one looks up is the key, and the definition of that word is the value.
In python, a dictionary is represented by curly braces with key and value pairs {key:value}.
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
print(student)
print(student['courses'])
Output:
{'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
['Math', 'CompSci']
The value could be any thing as strings, numbers, lists, tuples, and sets. And the key could be any immutable data type.
student = {1: 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
print(student[1])
Output:
John
If a key doesn’t exist, then it will return a KeyError.
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
print(student['phone'])
Output:
Traceback (most recent call last):
File "d:\Documents\Code\python\tutorial\5_dictionary.py", line 14, in <module>
print(student['phone'])
KeyError: 'phone'
Sometime, if a searching value is not in the dictionary, one would like to return None or a boolean value (True or False) rather than KeyError. The .get() method can solve this problem.
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
print(student.get('name'))
print(student.get('phone'))
Output:
John
None
We can change the output of the key that does not exist in the .get() method by assign a second value .get(key, assign_output).
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
print(student.get('phone', 'Not Found'))
Output:
Not Found
2. Add a New Entry to the Dictionary
To add a new entry to the existed dictionary, one can directly set the value to the key of that dictionary var_dict[key] = value. If a key already exists, then this will update the value of that key.
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
student['phone'] = '111-222-3333'
student['age'] = 22
print(student.get('phone', 'Not Found'))
print(student)
Output:
111-222-3333
{'name': 'John', 'age': 22, 'courses': ['Math', 'CompSci'], 'phone': '111-222-3333'}
2.1. Update Value
To update multiple values at a time,
.update() method will do the work by var_dict.update({key1:value1, key2:value2}).
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
student.update({'name': 'Jane', 'age': 26, 'phone': '111-222-3333'})
print(student)
Output:
{'name': 'Jane', 'age': 26, 'courses': ['Math', 'CompSci'], 'phone': '111-222-3333'}
3. Delete a Specific Key and its Value
3.1. del
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
del student['age']
print(student)
Output:
{'name': 'John', 'courses': ['Math', 'CompSci']}
3.2. .pop() method
The pop method allows to remove and grab the removed variable.
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
age = student.pop('age')
print(student)
print(age)
Output:
{'name': 'John', 'courses': ['Math', 'CompSci']}
25
4. Loop through the Keys and values
4.1. Dictionary - Length, Keys, and Values
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
print(len(student))
print(student.keys())
print(student.values())
print(student.items())
Output:
3
dict_keys(['name', 'age', 'courses'])
dict_values(['John', 25, ['Math', 'CompSci']])
dict_items([('name', 'John'), ('age', 25), ('courses', ['Math', 'CompSci'])])
4.2. Loop the Dictionary
- Loop only the key
The direct for loop will gives only the key but not the value.
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
for key in student:
print(key)
Output:
name
age
courses
- Loop through both key and value
By the .items() method, one can loop through both the keys and values of the dictionary.
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
for item in student.items():
print(item)
Output:
('name', 'John')
('age', 25)
('courses', ['Math', 'CompSci'])
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
for key, value in student.items():
print(key, value)
Output:
name John
age 25
courses ['Math', 'CompSci']
这篇文章介绍了Python中字典的数据结构,包括如何定义字典、添加新条目、更新值、删除特定键值对以及遍历字典的键和值。示例代码展示了使用`get()`方法避免`KeyError`,以及利用`del`和`pop()`方法删除元素。此外,还展示了如何通过循环遍历字典的键和值。
1068

被折叠的 条评论
为什么被折叠?



