码迷,mamicode.com
首页 > 编程语言 > 详细

python字典

时间:2021-04-01 13:38:17      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:image   技术   values   ict   默认值   get   key   符号   键值   

一、创建字典

字典特点:
  • 符号位大括号{}
  • 数据为键值对形式
  • 各个键值对之间用逗号隔开
# 1. 有数据的字典
dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}
print(dict1)

# 2. 创建空字典
dict2 = {}
print(type(dict2))  # <class ‘dict‘>

dict3 = dict()
print(type(dict3))  # <class ‘dict‘>

二、字典的常见操作

2.1 增

注意:如果key存在则修改这个key对应的值,如果key不存在则新增此键值对

dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}

# key存在,修改值
dict1[‘name‘] = ‘Rose‘
print(dict1)    # {‘name‘: ‘Rose‘, ‘age‘: 20, ‘gender‘: ‘male‘}

# key不存在,新增
dict1[‘id‘] = 110
print(dict1)    # {‘name‘: ‘Rose‘, ‘age‘: 20, ‘gender‘: ‘male‘, ‘id‘: 110}

2.2 删

  • del()/del:删除字典或字典中指定的键值对
dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}

# 1.del 删除字典或指定的键值对

# 删除字典
# del dict1
# print(dict1)    # NameError: name ‘dict1‘ is not defined

# 删除指定的键值对
del dict1[‘name‘]
print(dict1)    # {‘age‘: 20, ‘gender‘: ‘male‘}
  • clear():清空字典
dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}

# clear() 清空字典
dict1.clear()
print(dict1)    # {}

2.3 改

dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}

# key存在,修改值
dict1[‘name‘] = ‘Rose‘
print(dict1)    # {‘name‘: ‘Rose‘, ‘age‘: 20, ‘gender‘: ‘male‘}

2.4 查

2.4.1 key值查找

dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}

# 1.[key]
print(dict1[‘name‘])    # key存在,返回对应的值
# print(dict1[‘names‘])   # key不存在,报错

如果当前查找的key存在,则返回对应的值;否则报错

2.4.2 get()

  • 语法:
    dict.get(key,default)

注意:如果当前查找的key不存在则返回第二个参数(默认值),如果省略第二个参数,则返回None

dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}

# get()
print(dict1.get(‘name‘))  # Tom
print(dict1.get(‘id‘))  # None
print(dict1.get(‘id‘, 110))  # 110

2.4.3 keys()

dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}

# keys() 查找字典中所有的key,返回可迭代对象
print(dict1.keys())     # dict_keys([‘name‘, ‘age‘, ‘gender‘])

2.4.4 values()

dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}

# values() 查找字典中所有的values,返回可迭代对象
print(dict1.values())   # dict_values([‘Tom‘, 20, ‘male‘])

2.4.5 items()

dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}

# items() 查找字典中所有的键值对,返回可迭代对象,里面的数据是元组,元组数据1是字典的key,元组数据2是字典的values
print(dict1.items())    # dict_items([(‘name‘, ‘Tom‘), (‘age‘, 20), (‘gender‘, ‘male‘)])

三、字典的循环遍历

3.1 遍历字典的key

dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}

for key in dict1.keys():
	print(key)

技术图片

3.2 遍历字典的value

dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}

for value in dict1.values():
	print(value)

技术图片

3.3 遍历字典的元素

dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}

for item in dict1.items():
	print(item)

技术图片

3.4 遍历字典的键值对

dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}

for key,value in dict1.items():
	print(f‘{key} = {value}‘)

技术图片

python字典

标签:image   技术   values   ict   默认值   get   key   符号   键值   

原文地址:https://www.cnblogs.com/qian-yuan/p/14604732.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!