欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python字典的操作讲解

程序员文章站 2022-05-28 20:06:04
字典的出现:介于列表存储信息少,增删查改速度慢,出现了字典,用来存储更多种类信息,字典是一种key-value存储,key值不可变,可以是整数,字符串,不能是list,通过key值...

字典的出现:介于列表存储信息少,增删查改速度慢,出现了字典,用来存储更多种类信息,字典是一种key-value存储,key值不可变,可以是整数,字符串,不能是list,通过key值找value,每个key值只对应一个value.

字典定义:

(1)basketballplayer={'01':"Sun Dali",

'02':"Sun Xiaowei",

'03':"Da Ming",

'04':"Kobe",

"05":"ZhenMusi",

"06":"Blackmen",

"07":"Wang Dalu"}

(2)soccerplayer={"01":"David",

"08":"Li Yi",

"03":"Li Jinyu",

"09":"Wang Dalei"}

字典输出:print(basketballplayer) 结果为乱序

字典用法:(1)通过key找value print(basketballplayer['05'])

(2)通过key修改value basketballplayer['01']='Xiaowei'

print(basketballplayer['01'])

(3)通过不存在的key添加新的key value 用法同(2)

(4)删除某个key-value del basketballplayer['01']

basketballplayer.pop('02')

basketballplayer.popitem() #随便删一个

(5)查找某个value print('04' in basketballplayer) #首先通过key值判断是否在字典里

print(basketballplayer.get('04')) #上句返回真,则取出value

(6)打印所有value值 print(basketballplayer.values())

(7)打印所有key值 print(basketballplayer.keys())

(8)soccerplayer字典与basketballplayer字典合并,且有交叉用 soccerplayer字典更新basketballplayer字典 basketballplayer.update(soccerplayer)

print(basketballplayer)

(9)初始化一个value值相同的字典 newdict=dict.fromkeys([1,2,3],"cups")

print(newdict)

(10)修改(9)方式字典中的值 newdict=dict.fromkeys([1,2,3],[520,{"flower":"rose"},1314])

newdict[2][1]["flower"]="lily"

newdict[3][2]=666

print(newdict)

(11)字典变列表 print(basketballplayer.items())

(12)字典循环 for i in basketballplayer: #直接循环,i为key

print(i,basketballplayer[i])

for k,v in basketballplayer.items(): #将字典转为列表在循环,比直接循环费时

print(k,v)

(13)setdefault()用法 basketballplayer.setdefault("04","Xiaohua") #找到04号则不变否则创建新的key value

print(basketballplayer)