python基础笔记——字典

本文深入讲解了Python中字典的基本概念、创建、操作方法及内置函数。包括字典的建立、查询、增删改查、拼接、初始化、循环输出等操作,以及len()、str()、min()、max()等函数的使用。

字典

python中的字典使用{ }建立,每个元素是一个键值对,使用方式如下:

d = {key1 : value1, key2 : value2 }

key(键),必须唯一;value(值),可以重复
字典是无序的

d={3:"three",2:"two",4:"four",1:"one"}

1、查字典(一定要确定有该键)

print(d[3])
运行结果:three

2、增加

d[5] = "five"
print(d)
运行结果:{3: 'three', 2: 'two', 4: 'four', 1: 'one', 5: 'five'}

3、删除

del d
print(d)  #报错

标准删除

d={3:"three",2:"two",4:"four",1:"one"}
a = d.pop(2)
print(d)
运行结果:{3: 'three', 4: 'four', 1: 'one'}
print(a)
运行结果:two

随机删除

d.popitem()
print(d)
运行结果:{3: 'three', 2: 'two', 4: 'four'}

4、查找

print(d.get(3))
运行结果:three
#查找键值为3的值

print(4 in d)   #判断d中是否存在该键值,存在返回Ture,否则返回False
运行结果:Ture

5、打印所有的值

 print(d.values())
运行结果;dict_values(['three', 'two', 'four', 'one'])

6、打印所有的键

 print(d.keys())
运行结果: dict_keys([3, 2, 4, 1])

7、字典拼接

d1={3:"three",2:"two",4:"four",1:"one"}
d2={5:"three",6:"two",7:"four",8:"one"}
d1.update(d2)
print(d1)
#运行结果:{3: 'three', 2: 'two', 4: 'four', 1: 'one', 5: 'three', 6: 'two', 7: 'four', 8: 'one'}
#将d2拼接到d1的后面

8、打印所有项

print(d.items())
运行结果:dict_items([(3, 'three'), (2, 'two'), (4, 'four'), (1, 'one')])
#将一个键和它对应的值作为一个项

9、字典初始化

d=dict.fromkeys([2,3,4],"+++")
print(d)
运行结果:{2: '+++', 3: '+++', 4: '+++'}

10、将a作为键,b作为值

a=['name','age']
b=['wzq',19]
print(dict(zip(a,b)))
运行结果:{'name': 'wzq', 'age': 19}

11、字典的循环输出

for i in d:
     print(d[i])
运行结果:three
         two
         four
         one



for k,v in d.items():
     print(k,v)
运行结果:3 three
        2 two
        4 four
        1 one

字典的一些内置函数

函数描述
len(d)字典d的元素个数,即键的总数
str(d)输出字典,以可打印的字符串表示
min(d)字典d中键的最小值
max(d)字典d中键的最大值
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值