Python

Python数据类型_字典类型

2020-07-25  本文已影响0人  xilifeng

字典类型转换

t = [("name", "felix"), ("age", 18)]
res = dict(t)
print(res)
res = dict(a=1, b=2, c=3)
print(res)
keys = {"name", "age", "gender"}
res = {}.fromkeys(keys, None)
print(res)

字典类型的常用操作: key:value, value可以任意类型, key必须不可变类型, 不能重复, 通常为字符串

按key存取值: 可存可取

dic = {"name": "felix", "age": 18}
dic["gender"] = "male"  # key不存在则加值, key存在则改值
print(dic)

长度

dic = {"name": "felix", "age": 18, "gender": "male"}
print(len(dic))

成员运算in 和 not in

dic = {"name": "felix", "age": 18, "gender": "male"}
print("name" in dic)  # True
print("felix" in dic)  # False, 依据key判断

内置方法: get

dic = {"name": "felix", "age": 18, "gender": "male"}
res = dic.get("nametest")
print(res)  # None, 没取到返回None

内置方法: 键keys(), 值values(), 键值对items() 用在for循环

dic = {"name": "felix", "age": 18, "gender": "male"}
for k, v in dic.items():
    print(k, v)

内置方法: update

dic = {"name": "felix", "age": 18, "gender": "male"}
dic.update({"age": 20, "height": 1.8})
print(dic)

内置方法: setdefault 若更新的key存在, 则不改, 若不存在, 则新增, 有返回值

dic = {"name": "felix", "age": 18, "gender": "male"}
res = dic.setdefault("name", "richard")
print(res)

删除

dic = {"name": "felix", "age": 18, "gender": "male"}

方式1: 万能删除, 没有返回值

del dic["name"]
print(dic)

方式2: pop指定key删除, 返回删除的value

res = dic.pop("name")
print(res)

方式3: popitem随机删除

dic = {"name": "felix", "age": 18, "gender": "male"}
res = dic.popitem()
上一篇下一篇

猜你喜欢

热点阅读