Python 字典

字典

  • 字典是一系列键-值对。每个键都与一个值相关联。与键相关联的值可以是数字、字符串、列表、字典等。
Dormitory={'Number':205,'Content':"Fairies"}
print(Dormitory['Number'])
print(Dormitory['Content'])

输出结果

205
Fairies
  • 添加键-值对
Dormitory['Boss']="Yang"
print(Dormitory)

输出结果

{'Number': 205, 'Content': 'Fairies', 'Boss': 'Yang'}
  • 修改键值对
print(Dormitory['Boss'])
Dormitory['Boss']="Xiao"
print(Dormitory['Boss'])

输出结果

Yang
Xiao
  • 删除键值对
print(Dormitory)
del Dormitory['Boss']
print(Dormitory)

输出结果

{'Number': 205, 'Content': 'Fairies', 'Boss': 'Xiao'}
{'Number': 205, 'Content': 'Fairies'}
  • 遍历字典的键值对
Dormitory={'Number':205,'Content':"Fairies"}
for key,value in Dormitory.items():
	print("key:"+key)
	print("value:"+str(value))

输出结果

key:Number
value:205
key:Content
value:Fairies
  • 遍历字典的所有键
for dorm in Dormitory.keys():
	print(dorm)

输出结果

Number
Content
  • 遍历字典所有值
for value in Dormitory.values():
	print(str(value))

输出结果

205
Fairies
  • 字典列表
member_0={'Name':"Yang",'age':22}
member_1={'Name':"Liu",'age':21}
member_2={'Name':"Zhang",'age':21}
Members=[member_0,member_1,member_2]
for member in Members:
	print(member)

输出结果

{'Name': 'Yang', 'age': 22}
{'Name': 'Liu', 'age': 21}
{'Name': 'Zhang', 'age': 21}
  • 在字典中存储列表
Members={'member_3':['Zhang',20],'member_4':['Qian',21]
,'member_5':['Zhai',20]}
for key in Members:
	print(key)

输出结果

member_3
member_4
member_5

你可能感兴趣的:(Python,列表,python)