Python3 字典内置函数

Posted children92

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python3 字典内置函数相关的知识,希望对你有一定的参考价值。

如何定义一个字典?

info={
    "k1":18, #key:key值
    "k2":True,
    "k3":[11,22,{"kk1":"vv1","kk2":"vv2"}]
}
print(info)

运行结果:
{‘k1‘: 18, ‘k2‘: True, ‘k3‘: [11, 22, {‘kk1‘: ‘vv1‘, ‘kk2‘: ‘vv2‘}]}

字典可以进行多重嵌套
布尔值不能作为字典的key
列表不能作为字典的key
字典也不能作为字典的key
元组可以

而且字典是无序的,顺序不定

info={
    "k1":18,
    "k2":True,
    "k3":[11,22,{"kk1":"vv1","kk2":"vv2"}]
}

如何取到18

答案:print(info["k1"])

如何取到11

答案:print(info["k3"][0])

如何取到从vv1

print(info["k3"][2]["kk1"])

如何删除k1

del info["k1"]

如何删除kk2

del info["k3"][2]["kk2"]

字典能否for循环?
可以for循环,但是只能显示key 无法读取到key值

dict的函数:
#keys 获取字典的key

info={
    "k1":18,
    "k2":True,
    "k3":[11,22,{"kk1":"vv1","kk2":"vv2"}]
}
v=info.keys()
print(v)


运行结果:
dict_keys([‘k1‘, ‘k2‘, ‘k3‘])

#items 读取整个字典
如何获取到字典的key 和值

info={
    "k1":18,
    "k2":True,
    "k3":[11,22,{"kk1":"vv1","kk2":"vv2"}]
}
for k,v in info.items():
    print(k,v)

运行结果:

k1 18
k2 True
k3 [11, 22, {‘kk1‘: ‘vv1‘, ‘kk2‘: ‘vv2‘}]

#clear 清空整个字典

info={
    "k1":18,
    "k2":True,
    "k3":[11,22,{"kk1":"vv1","kk2":"vv2"}]
}
info.clear()
print(info)

运行结果:
{}


#copy函数,浅复制一个字典

info={
    "k1":18,
    "k2":True,
    "k3":[11,22,{"kk1":"vv1","kk2":"vv2"}]
}
v1=info.copy()
print(v1)

运行结果:
{‘k1‘: 18, ‘k2‘: True, ‘k3‘: [11, 22, {‘kk1‘: ‘vv1‘, ‘kk2‘: ‘vv2‘}]}

#fromkeys 传递序列,第一个参数作为key,第二个参数作为值

v=dict.fromkeys(["chen","chao","zhen"],111)
print(v)

 

运行结果:
{‘chen‘: 111, ‘chao‘: 111, ‘zhen‘: 111}

#get 取某个key的值,不存在会返回None,不会报错

 

v=dict.fromkeys(["chen","chao","zhen"],111)
print(v.get("kk1"))

运行结果:
None

v=dict.fromkeys(["chen","chao","zhen"],111)
print(v.get("chen"))

运行结果:
111

#pop  删除某个key 然后返回该key的值,如果该key没有 可以返回指定的值

v=dict.fromkeys(["chen","chao","zhen"],111)
v1=v.pop("chen")
print(v1)

运行结果:
111

v=dict.fromkeys(["chen","chao","zhen"],111)
v1=v.pop("abb",100)
print(v1)

运行结果:
100


#popitems 随机删除某个key 并返回key和key值

v=dict.fromkeys(["chen","chao","zhen"],111)
v1,v2=v.popitem()
print(v1,v2)

 

运行结果:
zhen 111

#setdefault 设置某个key的值,已经存在就获取当前key对应的值,不存在就插入该key

v=dict.fromkeys(["chen","chao","zhen"],111)
v1=v.setdefault("chen","123") #chen已经存在,返回key值
v.setdefault("b",12) #b不存在,插入字典
print(v,v1)

运行结果:
{‘chen‘: 111, ‘chao‘: 111, ‘zhen‘: 111, ‘b‘: 12} 111

#update 更新key和key值

v=dict.fromkeys(["chen","chao","zhen"],111)
v.update({"chen":99})
print(v)

运行结果:
{‘chen‘: 99, ‘chao‘: 111, ‘zhen‘: 111}

另外一种书写方式:

v=dict.fromkeys(["chen","chao","zhen"],111)
v.update(chen=99,chao=88,zhen=90)
print(v)

运行结果:
{‘chen‘: 99, ‘chao‘: 88, ‘zhen‘: 90}


























以上是关于Python3 字典内置函数的主要内容,如果未能解决你的问题,请参考以下文章

13 个非常有用的 Python 代码片段

[Python3]Dictionary(字典)

Python3 字典

Python3-内置数据类型-映射类型

python3字典

内置函数