Python字典的基础知识

版权声明:版权归本人,仅供大家参考 https://blog.csdn.net/Dream____Fly/article/details/82987648

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']}

猜你喜欢

转载自blog.csdn.net/Dream____Fly/article/details/82987648