字典是键值对无序可变序列
字典定义
a={"name":"onyy","age":"12"} #花括号定义字典
print(a)
b=dict(name="onyy",age="12")#用dict()创建字典
print(b)
c={} #定义一个空字典
print(c)
d=dict() #定义一个空字典
print(d)
结果为:
{‘name’: ‘onyy’, ‘age’: ‘12’}
{‘name’: ‘onyy’, ‘age’: ‘12’}
{}
{}
a1=[1,2,3]
b1=['w','e','r']
c1=dict(zip(a1,b1)) #用zip()创建字典
print(c1)
结果为:
{1: ‘w’, 2: ‘e’, 3: ‘r’}
字典的取值方法
1、通过键取值
a={"name":"ok","age":12}
print(a['name'])
结果为:ok
当你不确定你所需要的键的名称时,为了防止报错,使用get(键的名称,一个提示)
get()当字典里面有这个键时返回值,如果没有则返回一个提示
a={"name":"ok","age":12}
print(a.get("age","不好意思没有这个"))
print(a.get("okdhd","不好意思没有这个"))
结果为
12
不好意思没有这个
输出键值对、键、值
a={"name":"ok","age":12}
print(a.items()) #输出所有键值对
print(a.keys()) #输出所有键
print(a.values())#输出所有值
结果为:
dict_items([(‘name’, ‘ok’), (‘age’, 12)])
dict_keys([‘name’, ‘age’])
dict_values([‘ok’, 12])
len()查看键值对的个数
a={"name":"ok","age":12}
print(len(a))
结果为:2
遍历字典
1、直接遍历,输出为键的遍历
a={"name":"ok","age":12}
for i in a:
print(i)
结果为:
name
age
2、遍历键
a={"name":"ok","age":12}
for i in a.keys():
print(i)
结果为:
name
age
3、遍历值
a={"name":"ok","age":12}
for i in a.values():
print(i)
结果为:
ok
12
4、遍历键值对
a={"name":"ok","age":12}
for i in a.items():
print(i)
结果为:
(‘name’, ‘ok’)
(‘age’, 12)
字典元素添加、修改和删除
1、给字典新增键值对,如果键已经存在,则覆盖旧的键值对,如果键不存在则新增键值对
a={"name":"ok","age":12}
a["name"]="ooooo"
print(a)
结果为:{‘name’: ‘ooooo’, ‘age’: 12}
a={"name":"ok","age":12}
a["weight"]="90"
print(a)
结果为:{‘name’: ‘ok’, ‘age’: 12, ‘weight’: ‘90’}
2、使用update()将新字典中所有键值对全部添加到旧字典对象上,如果key(键)有重复,则直接覆盖
a={"name":"ok","age":22}
b={"name":"xiaoming","class":13}
a.update(b)
print(a)
结果为:{‘name’: ‘xiaoming’, ‘age’: 22, ‘class’: 13}
3、使用del clear .pop()删除
a={"name":"ok","age":22,"weight":323}
del a['name']
print(a)
结果为:{‘age’: 22, ‘weight’: 323}
a={"name":"ok","age":22,"weight":323}
b=a.pop('name')
print(a)
print(b) #使用.pop()有返回值
结果为:{‘age’: 22, ‘weight’: 323}
a={"name":"ok","age":22,"weight":323}
a.clear()
print(a)
结果为 : {}
.popitem()随机删除和返回键值对
a={"name":"ok","age":22,"weight":323}
b=a.popitem()
print(a)
print(b)
结果为:
{‘name’: ‘ok’, ‘age’: 22}
(‘weight’, 323)
序列解包用于字典时,默认是对键的操作,如果需要对键值对操作则需要使用items(),如果需要对值进行操作,则需要使用values()
键
a={"name":"ok","age":22,"weight":323}
b,c,d=a.keys()
print(b)
print(c)
print(d)
结果为:
name
age
weight
值
a={"name":"ok","age":22,"weight":323}
b,c,d=a.values()
print(b)
print(c)
print(d)
结果为:
ok
22
323
键值对
a={"name":"ok","age":22,"weight":323}
b,c,d=a.items()
print(b)
print(c)
print(d)
结果为:
(‘name’, ‘ok’)
(‘age’, 22)
(‘weight’, 323)
表格数据使用字典和列表
a={"name":"ok1","age":1,"weight":11}
b={"name":"ok2","age":2,"weight":22}
c={"name":"ok3","age":3,"weight":33}
d=[a,b,c]
for i in range(3):
print(d[i].get("name") ,d[i].get("age"),d[i].get("weight"))
结果为:
ok1 1 11
ok2 2 22
ok3 3 33