python字典介绍(一)

1.字典

字典与集合区别于序列类型,属于 无序 的数据集合体,即保存在字典与集合中的数据,没有特定顺序。 字典中的数据元素是 “关键字:值” 对,关键字相当于索引,它对应的值就是数据,关键字与值是唯一对应的。 关键字 必须是 不可变 类型数据,如整数、字符串,列表不能做关键字。 字典的关键字必须是可哈希的,字典 可变 类型。字典可包含任何类型的数据。字典的元素也可以是列表(不能做关键字)、元组或字典。

1.1 字典的创建

d1={}
d2={'name':'joe','age':25, 'seatnum':25,'studentID':156283}
print(d1)
print(d2)

运行结果:

d3={('name',2):'joe',('name',1):'Smith'}
print(d3)

运行结果:

 也可以使用dict()创建字典。如下代码所示:

#dict()创建空字典
d4=dict()
#用列表或元组作为dict()的参数
d5=dict(([1,'apple'],[2,'pear']))
#将数据按“关键字:值”的形式传递给dict()
d6=dict(name='joe',age=25,num=15628)
print(d4)
print(d5)
print(d6)

运行结果:

1.2 字典的访问

字典的元素通过其关键字访问,一般格式为字典名[关键字]。

d1={'name':'joe','age':25}
print(d1['age'])
d2={'name':{'first name':'joe','last name':'Smith'},'age':25}
print(d2['name'])
print(d2['name']['first name'])
d3={'name':'joe','score':(76,86,89)}
print(d3['score'][2])

运行结果:

1.3 字典的更新

更新字典的值也是通过该值的关键字进行,一般格式为字典名[关键字]=值 。

扫描二维码关注公众号,回复: 15945939 查看本文章
d4={'name':'joe','age':20,'num':168236}
d4['age']=22
d4['num']=168246
print(d4)

运行结果:

 字典也可以通过添加新的“关键字:值”对来扩展。

d4={'name':'joe','age':20,'num':168236}
d4['age']=22
d4['num']=168246
print(d4)
d4['score']=[87,79,92]
print(d4)
d5=dict()
d5['name']='joe'
d5['age']=12
print(d5)

 运行结果:

 1.4 字典元素的删除

d5={'name': {'Jane'}, 'age': 21, 'num': 168293, 'score': [88, 79, 92]}
del d5['score']
print(d5)

运行结果:

 1.5 检查字典关键字是否存在

关键字  in  字典,结果为True,表示关键字存在;

关键字  not in  字典,结果为True,表示关键字不存在.

d5={'name': {'Jane'}, 'age': 21, 'num': 168293, 'score': [88, 79, 92]}
del d5['score']
print(d5)
print('num' in d5)
print('score' not in d5)

 

1.6 字典的长度和运算

 Len()函数可以获得字典中“关键字:值”对的数目,即字典的长度。字典不支持+、*运算,支持==!=关系运算。list(dist)函数可以获得字典dist的关键字,并按顺序组成一个列表。

d6={'name': {'Simon'}, 'age': 20, 'num': 176293, 'score': [88, 79, 92]}
print(len(d6))
d7={'name': {'Simon'}, 'age': 21, 'num': 176298, 'score': [88, 89, 92]}
print(d7==d6)
print(list(d7))

运行结果:

猜你喜欢

转载自blog.csdn.net/higerwy/article/details/129960875