龙空技术网

5.python学习笔记-字典

吃饱了的饭团 57

前言:

此刻朋友们对“python 字典长度”都比较讲究,你们都想要知道一些“python 字典长度”的相关文章。那么小编在网摘上网罗了一些对于“python 字典长度””的相关知识,希望大家能喜欢,同学们快快来学习一下吧!

1.关于字典

字典是一类key-value键值对的无序集合,用于存储和查找唯一key的元素。字典提供了一个高效的方式来根据键访问和操作值。

python中可以使用大括号{}或者dict()函数创建字典,字典的键必须是唯一的且不可变的类型(如字符串、整数、浮点数、元组),值可以是任意类型的对象。

对比java,java有map相关的接口,是通过接口层面抽象的,具体有不同的实现类,比如:HashMap、TreeMap等。

2.常用操作

创建字典

# 创建空字典fruits = {}# 创建含有键值对的字典fruits = {'banana': 1, 'apple': 2, 'orange': 3}# 字典包含不同类型的键值对mixed = {1: 'hello', 'name': 'Alice', True: 3.14,'points':(2,3)}
访问字典

可以通过键来访问字典中的值,使用方括号 [] 运算符并指定键来访问对应的值。如果访问一个不存在的键,会引发 KeyError 错误。可以使用 get() 方法来避免这种情况,该方法返回键对应的值,如果键不存在则返回指定的默认值。

fruits = {'banana': 1, 'apple': 2, 'orange': 3}print(fruits)print(fruits['apple'])#KeyError: 'not exist'#print(fruits['not exist'])print(fruits.get('apple'))print(fruits.get('not exist',0))
输出结果:{'banana': 1, 'apple': 2, 'orange': 3}220
修改字典中的值

假设我们有一艘“飞船”,飞船的当前位置(x,y),根据飞船的速度类型speed设置飞船的增量移动距离increment,得到飞船新的位置。

ship={"name":"Ship1","position":(10,10),"speed":"slow"}print(f"飞船:{ship['name']},当前位置:{ship['position']},速度类型:{ship['speed']}")if ship['speed'] == 'slow':   increment=1elif ship['speed'] == 'medium':    increment = 2else:    increment = 3position_new=(ship['position'][0]+increment,ship['position'][1]+increment)ship['position']=position_newprint(f"飞船:{ship['name']},当前位置:{ship['position']},速度类型:{ship['speed']}")
输出结果:飞船:Ship1,当前位置:(10, 10),速度类型:slow飞船:Ship1,当前位置:(11, 11),速度类型:slow
删除键值对

使用del关键字删除键值对

fruits = {'banana': 1, 'apple': 2, 'orange': 3}print(fruits)del fruits['apple']print(fruits)
输出结果:{'banana': 1, 'apple': 2, 'orange': 3}{'banana': 1, 'orange': 3}
添加键值对
fruits = {'banana': 1, 'apple': 2}print(fruits)#直接添加fruits['orange']=3print(fruits)#使用update:update()方法可以接收另一个字典作为参数,#并将其键值对添加到当前字典中。del fruits['orange']fruits.update({'orange':3})print(fruits)#使用setdefault()方法:setdefault()方法在字典中查找键,#如果找到了则返回其值,如果没有找到,则会在字典中添加新的键值对,#不设置值,默认值为None。del fruits['orange']print(fruits.setdefault('orange',3))print(fruits)
输出结果:{'banana': 1, 'apple': 2}{'banana': 1, 'apple': 2, 'orange': 3}{'banana': 1, 'apple': 2, 'orange': 3}3{'banana': 1, 'apple': 2, 'orange': 3}
遍历字典

假设你买了几种水果,统计这几种水果一共花了多少钱。

fruits = {'banana': 1.1, 'apple': 2.3, 'orange': 3.5111}# 遍历键,也可以用fruits.keys()for key in fruits:    print(key)# 遍历值for value in fruits.values():    print(value)# 遍历键值对for key, value in fruits.items():    print(key, value)#统计花了多少钱sum=0.0names=set()for key,value in fruits.items():    sum+=value    names.add(key)#取小数点后两位sum=round(sum,2)print(f"水果:{names},一共花了{sum}")print(f"keys类型:{type(fruits.keys())}")print(f"values类型:{type(fruits.values())}")print(f"items类型:{type(fruits.items())}")
输出结果:bananaappleorange1.12.33.5111banana 1.1apple 2.3orange 3.5111水果:{'orange', 'apple', 'banana'},一共花了6.91keys类型:<class 'dict_keys'>values类型:<class 'dict_values'>items类型:<class 'dict_items'>

可以通过list()/set(),将fruits.keys()或者fruits.values()转换成列表/集合类型;默认键列表是无序的,可以通过sorted()函数进行排序。

print(set(fruits.keys()))print(list(fruits.values()))print(sorted(fruits.keys()))
输出结果:{'banana', 'apple', 'orange'}[1.1, 2.3, 3.5111]['apple', 'banana', 'orange']
嵌套

可以在列表/集合中嵌套字典、在字典中嵌套列表/集合,甚至在字典中嵌套字典。

fruits = {         'banana':{             'price':1.1         },         'apple':{              'price':2.3         },         'orange':{             'price':4.3         }}sum=0.0for key,value in fruits.items():    sum+=value['price']print(f"水果:{set(fruits.keys())},花了{round(sum,2)}")
输出结果:水果:{'apple', 'orange', 'banana'},花了7.7
其他常用操作

字典还支持获取长度、清空字典、判断键是否存在等操作。可以使用相应的方法来完成这些操作。

fruits = {'banana': 1.1, 'apple': 2.3, 'orange': 3.5111}# 获取字典长度length = len(fruits)print(length)# 检查键'apple'是否存在print('apple' in fruits)print('not exist' not in fruits)# 清空字典fruits.clear()print(fruits)
输出结果:3TrueTrue{}

标签: #python 字典长度 #python字典长度限制 #python字典长度怎么看 #python查看字典长度