字典的一些操作

Posted albatorss

tags:

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

字典

字典是python中唯一的映射类型,采用键值对(key-value)的形式存储数据。python对key进行哈希函数运算,根据计算的结果决定value的存储地址,所以字典是无序存储的,且key必须是可哈希的。可哈希表示key必须是不可变类型,如:数字、字符串、元组。

1.增

加入列表

dic = {name: Alisita, age: 45, hobbie: run}
dic[li] = [a]
print(dic)

#输出
    {name: Alisita, age: 45, hobbie: run, li: [a]}

无则添加

dic = {name: Alisita, age: 45, hobbie: run}
dic[high]=185
print(dic)

#输出
    {name: Alisita, age: 45, hobbie: run, high: 185}

有则覆盖

dic = {name: Alisita, age: 45, hobbie: run}
dic[name]=Delaiesi
print(dic)

#输出
    {name: Delaiesi, age: 45, hobbie: run}

setdefault

有键值对不作任何改变,没有才添加

dic = {name: Alisita, age: 45, hobbie: run}
dic.setdefault(weight‘,180)
print(dic)

#输出
    {name: Alisita, age: 45, hobbie: run, weight: 180}

 

2.删

pop     pop根据key删除键值对,并返回对应的值,如果没有key则返回默认返回值

dic = {name: Alisita, age: 45, hobbie: run}
dic_pop=dic.pop(name)
print(dic_pop)
print(dic)

#输出
    Alisita
{age: 45, hobbie: run}

popitem     随机删除字典中的某个键值对,将删除的键值对以元祖的形式返回

dic = {name: Alisita, age: 45, hobbie: run}
dic_pop=dic.popitem()
print(dic_pop)
print(dic)

#输出
    (hobbie, run)
{name: Alisita, age: 45}

clear   清空字典中的元素

dic = {name: Alisita, age: 45, hobbie: run}
dic.clear()
print(dic)

#输出
    {}

 

3.改

将dic所有的键值对覆盖添加(相同的覆盖,没有的添加)到dic1中

dic = {name: Alisita, age: 45, hobbie: run}
dic1 = {name: Aoraf, sex: male}
dic1.update(dic)
print(dic)
print(dic1)

#输出
    {name: Alisita, age: 45, hobbie: run}
    {name: Alisita, sex: male, age: 45, hobbie: run}

 

4.查

dic = {name: Alisita, age: 45, hobbie: run}
name = dic[name]
print(name)

#输出
    Alisita

get       dic.get(‘要查找的元素‘,设定的返回值)  #如果字典中没有要找的项,则返回设定的返回值,若果没有设定返回值,则返回,默认返回值

dic = {name: Alisita, age: 45, hobbie: run}
name = dic.get(sex,0)
print(name)

#输出
    0

dic = {name: Alisita, age: 45, hobbie: run}
name = dic.get(name,0)
print(name)

#输出
    Alisita

 

 

5.其他操作

dic = {name: Alisita, age: 45, hobbie: run}
for item in dic.items():
    print(item)

#items : ‘name‘: ‘Alisita‘
#keys :‘name‘
#values :‘Alisita‘

 

字典的循环

dic = {name: Alisita, age: 45, hobbie: run}
for key in dic:
    print(key)

#输出
    name
    age
    hobbie


dic = {name: Alisita, age: 45, hobbie: run}
for item in dic.items():
    print(item)

#输出
    (name, Alisita)
    (age, 45)
    (hobbie, run)


dic = {name: Alisita, age: 45, hobbie: run}
for key,value in dic.items():
    print(key,value)

#输出
    name Alisita
    age 45
    hobbie run

 

以上是关于字典的一些操作的主要内容,如果未能解决你的问题,请参考以下文章

Python代码阅读(第19篇):合并多个字典

Python代码阅读(第26篇):将列表映射成字典

Python代码阅读(第40篇):通过两个列表生成字典

如何有条件地将 C 代码片段编译到我的 Perl 模块?

VSCode自定义代码片段——git命令操作一个完整流程

python字典运用学习