# 增加/修改 # 如果key存在,就是修改值 # 如果key不存在,就是新增key和value dict = {"name":"刘备", "age":"15"} dict["name"] = "关羽" print(dict) dict["class"] = "1班" print(dict)
# 删除 一旦key删除了,则value也删除了 dict = {"name":"刘备", "age":"15"} dict.pop("name") print(dict)
# 清空 dict = {"name":"刘备", "age":"15"} dict.clear() print(dict)
# 得到key对应的值 dict = {"name":"刘备", "age":"15"} a = dict["name"] print(a)
dict = {"name":"周瑜", "age":"32", "id":"001"} dict["sex"] = "男" dict.pop("id") dict["age"] = "26" print(dict)
# 遍历字典 dict = {"name":"周瑜", "age":32, "id":"001"} for n in dict: print(n, dict[n]) # key n dict[n] value
# 通过items遍历字典 # 字典.items()返回一个包含key和value的元组 dict = {"name":"周瑜", "age":32, "id":"001"} # for n in dict.items(): # print(n) # 一旦使用了字典的items方法, n就是一个包含了key和value的元组 for n in dict.items(): # 对一个元组进行拆包 a, b = n print(a, b)
dict1 = { "a":23, "b": 4, "c": 9, "d": 3, "e": 12 } # for i in dict1: # print(i, dict1[i]) print("-------") for a, b in dict1.items(): print(a,b)
# 显示值9对应的key dict1 = { "a":23, "b": 4, "c": 9, "d": 3, "e": 12 } for n in dict1: if dict1[n] == 9: print(n)