1.定义
在{}内用逗号分隔开多元素,每一个元素都是key:value的形式,其中value可以是任意类型,而key则必须是不可变类型,通常key应该是str类型,因为str类型会对value有描述性的功能
info={'name':'tony','age':18,'sex':'male'}
info=dict(name='tony',age=18,sex='male') # info={'age': 18, 'sex': 'male', 'name': 'tony'}
2.类型转换
- 列表对应数量元素
>>> info=dict([['name','tony'],('age',18)])
>>> info
{'age': 18, 'name': 'tony'}
- fromkeys会从元组中取出每个值当做key,然后与None组成key:value放到字典中
>>> {}.fromkeys(('name','age','sex'),None)
{'age': None, 'sex': None, 'name': None}
3.字典的操作
-
按key存取,可存可取
- 取
dic = { 'name': 'xxx', 'age': 18, 'hobbies': ['play game', 'basketball'] } print(dic['name']) print(dic['hobbies'][1]) xxx basketball
- 对于赋值操作,如果key原先不存在于字典,则会新增key:value
dic['gender'] = 'male' print(dic) {'name': 'xxx', 'age': 18, 'hobbies': ['play game', 'basketball'], 'gender': 'male'}
- 对于赋值操作,如果key原先存在于字典,则会修改对应value的值
dic['name'] = 'tony' {'name': 'tony', 'age': 18, 'hobbies': ['play game', 'basketball']}
-
长度len
print(len(dic)) 3
-
成员运算
res ='name' in dic print(res) True
-
删除
>>> dic.pop('name') # 通过指定字典的key来删除字典的键值对 >>> dic {'age': 18, 'hobbies': ['play game', 'basketball']}
-
键keys(),值values(),键值对items()
dic = {'age': 18, 'hobbies': ['play game', 'basketball'], 'name': 'xxx'}
- 获取字典所有的key
>>> dic.keys() dict_keys(['name', 'age', 'hobbies'])
- 获取字典所有的value
>>> dic.values() dict_values(['xxx', 18, ['play game', 'basketball']])
- 获取字典所有的键值对
dic.items() dict_items([('name', 'xxx'), ('age', 18), ('hobbies', ['play game', 'basketball'])])
-
循环
- 默认遍历的是字典的key
>>> for key in dic: ... print(key) ... age hobbies name
- 只遍历key
>>> for key in dic.keys(): ... print(key) ... age hobbies name
- 只遍历value
>>> for key in dic.values(): ... print(key) ... 18 ['play game', 'basketball'] xxx
- 遍历key与value
>>> for key in dic.items(): ... print(key) ... ('age', 18) ('hobbies', ['play game', 'basketball']) ('name', 'xxx')
4.字典的进阶
-
get()
>>> dic= {'k1':'jason','k2':'Tony','k3':'JY'} >>> dic.get('k1') 'jason' # key存在,则获取key对应的value值 >>> res=dic.get('xxx') # key不存在,不会报错而是默认返回None >>> print(res) None >>> res=dic.get('xxx',666) # key不存在时,可以设置默认返回的值 >>> print(res) 666 # ps:字典取值建议使用get方法
-
pop()
>>> dic= {'k1':'jason','k2':'Tony','k3':'JY'} >>> v = dic.pop('k2') # 删除指定的key对应的键值对,并返回值 >>> dic {'k1': 'jason', 'kk2': 'JY'} >>> v 'Tony'
-
popitem()
>>> dic= {'k1':'jason','k2':'Tony','k3':'JY'} >>> item = dic.popitem() # 随机删除一组键值对,并将删除的键值放到元组内返回 >>> dic {'k3': 'JY', 'k2': 'Tony'} >>> item ('k1', 'jason')
-
update()
# 用新字典更新旧字典,有则修改,无则添加 >>> dic= {'k1':'jason','k2':'Tony','k3':'JY'} >>> dic.update({'k1':'JN','k4':'xxx'}) >>> dic {'k1': 'JN', 'k3': 'JY', 'k2': 'Tony', 'k4': 'xxx'}
-
fromkeys()
>>> dic = dict.fromkeys(['k1','k2','k3'],[]) >>> dic {'k1': [], 'k2': [], 'k3': []}
-
setdefault()
# key存在则不做任何修改,并返回已存在key对应的value值 >>> dic={'k1':111,'k2':222} >>> res=dic.setdefault('k1',666) >>> res 111 >>> dic # 字典不变 {'k1': 111, 'k2': 222}