python字典的增删改查等内置方法

#__author: "Pizer Wang"
#__date: 2018/1/28

dic = {"name":"Pizer"}
print(dic)

dic["age"] = 18
print(dic)

dic["name"] = "Jone"
print(dic)

#键存在的话不改动,返回字典中相应的键对应的值
age = dic.setdefault("age", 20)
print(dic)
print(age)

#键不存在的话,增加新的键值对并返回相应的值
hobby = dic.setdefault("hobby", "read")
print(dic)
print(hobby)

#查 通过键去查找
dic = {'name': 'Jone', 'age': 18, 'hobby': 'read'}
print(dic["name"])

#查看字典中所有的键
print(dic.keys())
print(type(dic.keys()))
print(list(dic.keys()))
print(list(dic.values()))
print(list(dic.items()))

#改 通过键去查找
dic = {'name': 'Jone', 'age': 18, 'hobby': 'read'}
dic["age"] = 22
print(dic)

dic_app = {"age":26, "sex":"male"}
#已有的键值对会被新的键值对覆盖,没有会添加
dic.update(dic_app)
print(dic)
print(dic_app)

#删
dic = {'name': 'Jone', 'hobby': 'read', 'sex': 'male', 'age': 26}

#删除字典中指定的键值对
del dic["name"]
print(dic)

#删除字典中的键值对并返回
age = dic.pop("age")
print(dic)
print(age)

#随机删除键值对,并返回
item = dic.popitem()
print(dic)
print(item)

#清空字典
dic.clear()
print(dic)

#删除字典
del dic
#打印会报错,内存中已不再有该对象
print(dic)

执行结果:
{‘name’: ‘Pizer’}
{‘age’: 18, ‘name’: ‘Pizer’}
{‘age’: 18, ‘name’: ‘Jone’}
{‘age’: 18, ‘name’: ‘Jone’}
18
{‘age’: 18, ‘hobby’: ‘read’, ‘name’: ‘Jone’}
read
Jone
dict_keys([‘age’, ‘hobby’, ‘name’])

你可能感兴趣的:(python基础)