Python入门之字典dictionary

# 字典不支持下标,以键值对形式出现, 各个键值对之间用逗号隔开
dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}  # 有数据的字典
dict2 = {}  # 空字典
dict3 = dict()
print(dict1)
print(type(dict1))
print(type(dict3))
# 字典常见操作
# 1.add
dict1['id'] = 110
print(dict1)
dict1['name'] = 'Rose'
print(dict1)
# 2.delete : del()/del /clear
del dict1['name']
print(dict1)
dict1.clear()  # 清空
print(dict1)
# 3.modify,如果存在则修改,不存在则新增
dict1['name'] = 'Lily'
dict1['id'] = 110
print(dict1)
# 4.1search,key值查找/get()——字典序列.get(key, 默认值)
print(dict1['name'])
print(dict1.get('name'))
print(dict1.get('gender', 'boy'))
print(dict1.get('gender'))  # key不存在则返回none
# 4.2 keys() 返回键值
print(dict1.keys())  # dict_keys(['name', 'id'])
# 4.3 values() 返回值
print(dict1.values())  # dict_values(['Lily', 110])
# 4.4 items() 返回元组,每个元组都是一个键值对
print(dict1.items())  # dict_items([('name', 'Lily'), ('id', 110)])
# 5 字典的遍历
dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
# 5.1 遍历字典的key
for key in dict1.keys():
    print(key)
# 5.2 遍历字典的value
for value in dict1.values():
    print(value)
# 5.3 遍历字典的item
for item in dict1.items():
    print(item)
# 5.4 字典遍历的键值对(拆包),内部是元组,元组有2个数据,数据1是字典的Key.数据2是字典的value
for key, value in dict1.items():
    print(f'{key} = {value}')
    print(key)
    print(value)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值