2018-10-26
阅读量:
755
Python字典类型
字典类型是Python中一种非序列的存储结构,存储的是键值对(key:value),其存储形式为 d={key1:value1, key2:value2},其中<键>是唯一不重复的,<值>可以不唯一。
# ==== 构建字典类型数据 ====
students={"203-2012-045":"John","203-2012-037":"Peter"} # 大括号创建字典
# 输出结果
print(students)
{'203-2012-045': 'John', '203-2012-037': 'Peter'}
# ==== 向已有字典里增加数据项 ====
students["202-2011-121"]="Susan" # 中括号添加字典
# 输出结果
print(students)
{'203-2012-045': 'John', '203-2012-037': 'Peter', '202-2011-121': 'Susan'}
# ==== 查询字典中的值 ====
students["203-2012-045"]
# 输出结果
'John'
# ==== 删除字典中的一项 ====
del students["203-2012-037"]
# 输出结果
print(students)
{'203-2012-045': 'John', '202-2011-121': 'Susan'}
# ==== 字典遍历 ====
for key in students:
print(key) # 输出key值
print(students[key]) # 输出value值
print(key + ":" + str(students[key])) # 输出key-value值
# 输出结果
203-2012-045
John
203-2012-045:John
==============
202-2011-121
Susan
202-2011-121:Susan
# ==== 判断键key是否在字典中 ====
"203-2012-045" in students # Output显示True/False
# 输出结果
True
# ==== 构建字典类型数据 ====
students={"203-2012-045":"John","203-2012-037":"Peter"}
# ==== 显示字典中所有的key ====
tuple(students.keys())
# 输出结果
('203-2012-045', '203-2012-037')
# ==== 显示字典中所有的value ====
tuple(students.values())
# 输出结果
('John', 'Peter')
# ==== 显示字典中所有的key-value ====
tuple(students.items())
# 输出结果
(('203-2012-045', 'John'), ('203-2012-037', 'Peter'))
# ==== 获取字典中key对应的值 ====
students.get("203-2012-045")
# 输出结果
'John'
# ==== 删除字典中key对应的值 ====
students.pop("203-2012-045")
students
# 输出结果
'John'
{'203-2012-037': 'Peter'} #students中删除了'John'
# ==== 删除字典中所有的值 ====
students.clear()
students
# 输出结果
{} #students被清空






评论(0)


暂无数据
推荐帖子
0条评论
0条评论
0条评论