Python Tutorial - 4 - Dictionary

这篇文章介绍了Python中字典的数据结构,包括如何定义字典、添加新条目、更新值、删除特定键值对以及遍历字典的键和值。示例代码展示了使用`get()`方法避免`KeyError`,以及利用`del`和`pop()`方法删除元素。此外,还展示了如何通过循环遍历字典的键和值。
摘要由CSDN通过智能技术生成

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']
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值