Python学习笔记之四:Python中的字典

Python学习笔记之四:Python中的字典

1 Python中字典的定义

Python中的字典是一系列键-值对的集合。每个键都有一个值与之关联,我们可以使用键来获取与之关联的值。该值可以是数字,字符串,列表甚至是字典。可以将Python中的任何对象用作字典中的值

2 Python中字典的使用方法

2.1 字典的基本使用方法

2.1.1 创建字典

可以使用一对空的花括号定义一个空字典,再为其添加键-值对,也可以直接定义一个包含多个键-值对的字典,具体使用方法如下实例所示:

#方法一
car = {'color':'red','type':'SUV','age':2}
print("The color of my car is: " + car['color'])
print("The type of my car is: " + car['type'])
#方法二
car = {}
car['color'] = 'red'
car['type'] = 'SUV'
car['age'] = 2
print("The color of my car is: " + car['color'])
print("The type of my car is: " + car['type'])

上述代码的运行结果如下:

The color of my car is: red
The type of my car is: SUV
2.1.2 访问字典中的值

要想访问字典中与某个键关联的值,可以通过字典名+键获取,具体使用方法如2.2.1中的实例中方法二所示

2.1.3 向字典中添加键-值对

字典是一个动态结构,可以随时向其中添加键-值对。具体使用方法如2.2.1中的实例中方法二所示

2.1.4 修改字典中的值

直接根据字典名与键对其进行重新赋值即可,具体使用方法如下实例所示:

car = {'color':'red','type':'SUV','age':2}
print("The color of my first car is: " + car['color'])
car['color'] = 'black'
print("The color of my second car is: " + car['color'])

上述代码的运行结果如下:

The color of my first car is: red
The color of my second car is: black
2.1.5 删除字典中的某个键-值对

使用del语句删除字典中指定的键-值对,具体使用方法如下实例所示:

car = {'color':'red','type':'SUV','age':2}
print(car)
del car['age']
print(car)

上述代码的运行结果如下:

{'color': 'red', 'type': 'SUV', 'age': 2}
{'color': 'red', 'type': 'SUV'}

2.2 字典的遍历

2.2.1 遍历字典中所有的键-值对

使用for循环与item()方法遍历字典中所有的键-值对,具体使用方法如下实例所示:

car = {'color':'red','type':'SUV','age':2}
for key,value in car.items():
	print("\nKey: " + key)
	print("Value: " + str(value))

上述代码的运行结果如下:

Key: color
Value: red

Key: type
Value: SUV

Key: age
Value: 2
2.2.2 遍历字典中所有的键

使用for循环与key()方法遍历字典中所有的键,具体使用方法如下实例所示:

car = {'color':'red','type':'SUV','age':2}
for key in car.keys():
	print("Key: " + key)

上述代码的运行结果如下:

Key: color
Key: type
Key: age
2.2.3 遍历字典中所有的值

使用for循环与values()方法遍历字典中所有的值,具体使用方法如下实例所示:

car = {'color':'red','type':'SUV','age':2}
for value in car.values():
	print("value: " + str(value))

上述代码的运行结果如下:

value: red
value: SUV
value: 2
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值