字典

数据类型-字典

字典是一种key-value的数据类型,字典通过key拿到value。使用就像我们上学用的字典,通过笔画,字母来查对应也的详细内容。

一、特性:
1、key-value结构
2、key必须可hash且必须为不可变数据类型,必须唯一
3、可存放任意多个值,可修改,可以不唯一
4、无序
5、查找速度快

在Python中,字符串、整数等都是不可变的,因此,可以放心地作为key。而list是可变的,就不能作为key

有序字典
无序字典

二、字典格式

info = {
"stud001": "xiaoming",
"stud002": "xiaohong",
"stud003": "xiaodong",
"stud004": "xiaomei"
}

三、增加

info["stud005"] = "xiao"
print(info.setdefault("stud004","martin"))   #key存在时打印对应value
print(info.setdefault("stud005","martin"))   #key不存在时增加


四、删除

info.pop("stud001")   #指定删除
info.popitem()        #随机删除
del info["stud002"]   #python的删除方法

五、修改

info["stud001"] = "xiao"
info["stud001"] += ",xiao"
{'stud001': 'xiaoming,xiao', 'stud002': 'xiaohong', 'stud003': 'xiaodong', 'stud004': 'xiaomei'}

六、查询

print(info["stud001"])     #该方法当key不存在时会报错
"stud003" in info          #标准用法,判断key是否在字典里,存在未Ture,不存在为False
print(info.get("stud001")) #这个不会,不存在会返回none

避免key不存在的错误,有两种办法:
1、是通过in判断key是否存在
'key' in dict
2、通过dict提供的get方法,如果key不存在,可以返回None,或者自己指定的value:
dict.get('key')
dict.get('key', -1)

七、字典循环
循环打印出字典中的key和value

#方法1
for key in info:
print(key,info[key])

#方法2
#dict.items()     #将字典转成列表,数据大时莫用
for k,v in info.items():
print(k,v)

八、字典合并

>>> info
{'stud001': 'xiaoming', 'stud002': 'xiaohong', 'stud003': 'xiaodong', 'stud004': 'xiaomei'}
>>> b
{1: 2, 3: 4}
>>> info.update(b)
>>> info
{'stud001': 'xiaoming', 'stud002': 'xiaohong', 'stud003': 'xiaodong', 'stud004': 'xiaomei', 1: 2, 3: 4}


九、其他操作

print(info.keys())   #获取字典的key列表
print(info.values()) #获取字典的value列表
print(info.items())  #将字典转换成列表
dict_items([('stud001', 'xiaoming'), ('stud002', 'xiaohong'), ('stud003', 'xiaodong'), ('stud004', 'xiaomei')])

十、字典的方法
maketrans方法是将两个字符串转成字典,匹配对应关系

>>> str_in = 'abcdefghij'
>>> str_out = '!@#$%^&*()'
>>> table = str.maketrans(str_in,str_out)
>>> table
{97: 33, 98: 64, 99: 35, 100: 36, 101: 37, 102: 94, 103: 38, 104: 42, 105: 40, 106: 41}
>>> 'jbcidefgha'.translate(table)
')@#($%^&*!'

 

 

原文地址:https://www.cnblogs.com/jmaly/p/8000132.html