Python:字典

xiaoxiao2021-02-27  158

一、字典

键key——值value

python的字典在很多地方也称为哈希值hash或者关系数组;

字典是Python中唯一的一种映射类型;一对一或者多对一;花括号

>>> brand = ['lining', 'nike', 'addiss', 'yuc'] >>> slogan = ['all inpassbale', 'just do it', 'impossible is nothing', 'coding change world'] >>> print('the word of yuc is:', slogan[brand.index('yuc')]) 不简洁,效率也不高 the word of yuc is: coding change world >>> dict1 = {'lining':'all impassbale', 'nike':'just do it', 'yuc':'coding change world'} 使用字典,创建 >>> print('the word of yuc is:', dict1['yuc']) 引用 the word of yuc is: coding change world

用dict()创建字典,是个工厂函数类型),严格上讲不是bif

dict1 = {} 创建空字典 dict() dict1 = dict((('a', 1), ('b', 2), ('c', 3)))传进去的是映射关系,这里用的是元组,也可用用列表;dict(mapping) dict1 = dict(小甲鱼=‘让编程改变世界’, 苍井空=‘让av征服宅男’) 小甲鱼加上引号会报错 dict4['d'] = '4 添加和修改

二、字典的内建方法dir(dict)

从序列键和值设置为value来创建一个新的字典

fromkeys()      不能用它来修改字典键值

>>> dict1 = {} >>> dict1 = dict1.fromkeys((1,2,3)) {1: None, 2: None, 3: None} >>> dict = dict1.fromkeys((1,2,3),'Number') {1: 'Number', 2: 'Number', 3: 'Number'} >>> dict1 = dict.fromkeys((1,2,3), ('one', 'two', 'three')) {1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}

访问:

for key in dict1.keys(): for value in dict1.values(): for item in dict1.items():用元组返回(k,v) for k, v in dict1.items()

访问时当键不存在时会报错keyerror;所以有个get()方法

dict1.get(4)        #4不存在,返回None

dict1.get(4, 'not  in')     #4不存在,返回"not in"

可以用in判断key是否在

dict1.setdefault(4, 'a')   #4不存在,创建4 : ‘a‘

dict1.setdefault(4)     #4不存在,创建4 : None

清空字典,建议使用clear()方法

dict1.clear() dict1 = {} 用这个方法不严谨,因为当两个变量指向一个对象时,将一个变量赋值为{},实际另一个还在映射着,所以还会存在 拷贝:

dict1.copy()浅拷贝(可以用id看,id不一样) 弹栈:

dict1.pop(key)给定键弹出值 dict1.popitem()随机弹出一个,因为字典里没有顺序

更新:

a = {1:'one', 2:'two'} b = {1: 'yi'} a.update(b)用b跟新a 返回{1:'yi', 2:'two'}

转载请注明原文地址: https://www.6miu.com/read-13156.html

最新回复(0)