Python字典的基础知识

本文详细介绍了Python字典的基本操作,包括查找、增加、删除字典元素,以及字典的拼接、初始化等高级用法。通过实例演示了字典在Python编程中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.注意事项:

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

2.查字典中的值:

d={1:"one",2:"two",3:"three",4:"four"}
print(d[2])
	输出结果:two

3.增加数组中的值:

d={1:"one",2:"two",3:"three",4:"four"}
d[5]="a"
print(d)
	输出结果:d={1:"one",2:"two",3:"three",4:"four",5:"a"}

4.删除字典中的值:—直接报错

d={1:"one",2:"two",3:"three",4:"four"}
del d
print(d)
	输出结果:Traceback (most recent call last):
			  File "E:/python/wenjie/笔记/字典.py", line 14, in <module>
	 		   print(d)
			NameError: name 'd' is not defined

5.删除字典中的值:—标准删除

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

6.删除字典中的值:—随机删除

d={1:"one",2:"two",3:"three",4:"four"}
d.popitem() 
print(d)
	输出结果:随机删除其中一个

7.查找字典中的值:

d={1:"one",2:"two",3:"three",4:"four"}
print(d.get(3))
print(4 in d)   #判断d中是否存在该键值
	输出结果:three
		 true

8.打印字典中的所有值:

d={1:"one",2:"two",3:"three",4:"four"}
print(d.values())
	输出结果:dict_values(['three', 'two', 'four', 'one'])

9.打印字典中的所有键:

d={1:"one",2:"two",3:"three",4:"four"}
print(d.keys())
	输出结果:dict_keys([3, 2, 4, 1])

10.字典拼接:

d={1:"one",2:"two",3:"three",4:"four"}
d2={5:"three",6:"two",7:"four"}
d.update(d2)
print(d)
	输出结果:
	d={1:"one",2:"two",3:"three",4:"four",5:"three",6:"two",7:"four"}

11.打印所有项:

d={1:"one",2:"two",3:"three",4:"four"}
print(d.items())
	输出结果:dict_items([(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')])

12.字典初始化:

c=dict.fromkeys([1,2,3],"Python")
print(c)
	输出结果:{1: 'Python', 2: 'Python', 3: 'Python'}

fromkeys现象说明

c=dict.fromkeys([1,2,3],[1,{"a":"A"},"Python"])
print(c)
c[3][1]["a"]="AAA"
print(c)
	输出结果:
{1: [1, {'a': 'A'}, 'Python'], 2: [1, {'a': 'A'}, 'Python'], 3: [1, {'a': 'A'}, 'Python']}
{1: [1, {'a': 'AAA'}, 'Python'], 2: [1, {'a': 'AAA'}, 'Python'], 3: [1, {'a': 'AAA'}, 'Python']}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值