特性:
dict无序key唯一,天生去重
常用函数
dict.clear() 删除字典中所有元素
dict.copy() 返回字典(浅复制)的一个副本
dict.
get(
key,
default=None) 对字典dict中的键
key,返回它对应的值value,如果字典中不存在此键,则返回
default 的值(注意,参数
default 的默认值为None)
dict.has_key(
key) 如果键(
key)在字典中存在,返回
True,否则返回
False
dict.items() 返回一个包含字典中(键, 值)对元组的列表
dict.keys() 返回一个包含字典中键的列表
dict.values() 返回一个包含字典中所有值的列表
dict.pop(
key[,
default]) 和方法
get()相似,如果字典中
key 键存在,删除并返回dict[
key],如果
key 键不存在,且没有给出
default 的值,引发KeyError 异常。
参考:Python中dict字典使用方法
创建字典
way 1:(小心列表坑!)
d = dict.fromkeys([
1,
2,
3], [
"name",
"age"])
print(
"d:", d)
d[
1][
0] =
"company"
print(
"d of modify:", d)
way 2:
info = {
"teacher1":
"苍井空",
"teacher2":
"小泽玛利亚",
"teacher3":
"泷泽萝拉"
}
字典无序输出
print(
"info", info)
查询
print(info[
"teacher1"])
print(info.get(
"teacher5"))
print(
"teacher1" in info)
print(
"keys:", info.keys())
print(
"values:", info.values())
print(
"items:", info.items())
修改
info[
"teacher1"] =
"天海翼"
print(
"modify:", info)
增加
info[
"teacher4"] =
"上原瑞穗"
info.setdefault(
"teacher1",
"樱井莉亚")
print(
"add:", info)
b = {
"teacher1":
"樱井莉亚",
"teacher5":
"桃谷绘里香"
}
info.update(b)
print(
"update:", info)
删除
del info[
"teacher1"]
info.pop(
"teacher2")
info.popitem()
print(
"delete:", info)
遍历
for i
in info:
print(i, info[i])
print(
"*"*
50)
for key, value
in info.items():
print(key, value)
清空
info.clear()
print(
"clear:", info)