一: 概述
- 字典是有大括号,逗号分隔,有k/v组成
- 字典的键必须hashable,如数字,字符串,布尔值,元组
二: 操作
2.1 增
2.1.1 直接赋值
- 如果键不存在,则增加
dic = {'name': 'wangys','age': 18}
dic['sex'] = 'male'
print(dic)
# {'name': 'wangys', 'age': 18, 'sex': 'male'}
- 如果键存在,则修改
dic = {'name': 'wangys','age': 18}
dic['name'] = 'wc'
print(dic) # {'name': 'wc', 'age': 18}
2.1.2 sedefault
- 如果键不存在,则增加
dic = {'name': 'wangys','age': 18}
dic.setdefault('sex','male')
print(dic)
# {'name': 'wangys', 'age': 18, 'sex': 'male'}
- 如果键存在,不过做更改
dic = {'name': 'wangys','age': 18}
dic.setdefault('name','wc')
print(dic)
# {'name': 'wangys', 'age': 18}
2.2 删
2.2.1 pop
- 如果键存在,则删除这个k/v
- 返回值为删除键的value值
dic = {'name': 'wangys','age': 18}
ret = dic.pop('age')
print(ret)
print(dic) #
# {'name': 'wangys'}
- 如果键不存在,则报错 KeyError
dic = {'name': 'wangys','age': 18}
ret = dic.pop('male')
print(ret)
print(dic)
# KeyError: 'male'
2.2.2 del
- 键如果存在,则删除
- 如果不存在,则包错 KeyError
dic = {'name': 'wangys','age': 18}
del dic['name']
print(dic)
del dic['male']
print(dic) # {'age': 18}
# KeyError: 'male'
2.2.3 clear
dic = {'name': 'wangys','age': 18}
dic.clear()
print(dic)
#{}
2.2.4 popitem
- 随机删除一个元素
- 返回值为kv组成的元祖
dic = {'name': 'wangys','age': 18}
print(dic.popitem())
print(dic)
# ('age', 18)
# {'name': 'wangys'}
2.3 改
2.3.1 直接修改
dic = {'name': 'wangys','age': 18}
dic['name'] = 'wc'
print(dic)
# {'name': 'wc', 'age': 18}
2.3.2 update
- 两个字典合并
- 如果键冲突,则更新,如果不冲突则增加
dic1 = {'name': 'wangys','age': 18}
dic2 = {'name': 'wc','sex': 'male'}
dic1.update(dic2)
print(dic1)
# {'name': 'wc', 'age': 18, 'sex': 'male'}
2.4 查
2.4.1 直接查
- 如果键不存在,则报错,KeyError
dic1 = {'name': 'wangys','age': 18}
print(dic1['name'])
# wangys
dic1 = {'name': 'wangys','age': 18}
print(dic1['male'])
# KeyError: 'male'
2.4.2 get
- 如果不存在,则返回None,也可以指定返回值
dic1 = {'name': 'wangys','age': 18}
ret1 = dic1.get('name')
ret2 = dic1.get('male')
ret3 = dic1.get('male','改键不存在')
print(ret1,ret2,ret3)
# wangys None 改键不存在
2.4.3 setdefault
name = {'name': 'wangys','age': 18}
print(name.setdefault('name'))
# wangys
三: 其他操作
3.1 for 循环
- 得到的是key
- for循环字典时不允许对字典进行增删
dic1 = {'name': 'wangys','age': 18}
for item in dic1:
print(item)
# name
# age
# 直接删除字典中的元素会报错
dic = {'k1':1,'k2':2}
for el in dic:
dic.pop(el)
# RuntimeError: dictionary changed size during iteration
3.2 keys
- 返回值是由key组成的特殊列表
- 是可迭代的,可以被for循环
dic1 = {'name': 'wangys','age': 18}
ret = dic1.keys()
print(ret)
# dict_keys(['name', 'age'])
dic1 = {'name': 'wangys','age': 18}
ret = dic1.keys()
for key in ret:
print(key)
3.3 values
- 返回值是由values值组成的特殊列表
- 是可迭代的,可以被for循环
dic1 = {'name': 'wangys','age': 18}
ret = dic1.values()
print(ret)
#dict_values(['wangys', 18])
3.4 items
- 是有key value组成的小元组后再次组成一个特殊列表,可迭代,可以被for循环
dic1 = {'name': 'wangys','age': 18}
ret = dic1.items()
print(ret)
# dict_items([('name', 'wangys'), ('age', 18)])
四: 练习题
# 将 s = 'k1:1|k2:2|k3:3' 改为{'k1': 1, 'k2': 2, 'k3': 3}
s = 'k1:1|k2:2|k3:3'
new_list = s.split('|')
dic = {}
for item in new_list:
k,v = item.split(':')
dic[k] = int(v)
print(dic)
# li中的数字,如果大于66 就加入k1的列表中,否则添加到k2的列表中
li = [11,22,33,44,55,66,77,88,99,90]
dic = {'k1': [],'k2': []}
for item in li:
if item == 66:continue
elif item > 66:
dic.setdefault('k1').append(item)
else:
dic.setdefault('k2').append(item)
print(dic)
# 打印序号,商品名称,价格
用户选择序号,打印商品名和价格
选择q,退出
goods = [
{'name': '电脑','price': ''},
{'name': '手表','price': ''},
{'name': '衬衣','price': ''},
{'name': '裤子','price': ''},
]
while 1:
for index in range(1,len(goods)+1):
print(index,goods[index-1]['name'],goods[index-1]['price'])
choice = input('请输入序号: ').strip()
if choice.upper() == 'Q':
break
elif choice and choice.isdigit():
choice = int(choice)
if choice >0 and choice <= len(goods):
print(goods[choice-1]['name'],goods[choice-1]['price'])
else:
print('请输入范围内的序号')
else:
print('请输入正确的序号')
字典数据操作实例
对字典列表排序及字典列表最小最大值
rows = [
{'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},
{'fname': 'David', 'lname': 'Beazley', 'uid': 1002},
{'fname': 'John', 'lname': 'Cleese', 'uid': 1001},
{'fname': 'Big', 'lname': 'Jones', 'uid': 1004}
] from operator import itemgetter
import pprint rows_by_fname = sorted(rows, key=lambda x: x['fname'])
rows_by_fname_ir = sorted(rows, key=itemgetter('fname'))
min_item = min(rows, key=itemgetter('fname'))
max_item = max(rows, key=itemgetter('fname'))
pprint.pprint(rows_by_fname)
pprint.pprint(rows_by_fname)
print(min_item)
print(max_item)