一、字典简介
字典在Python里是无序集合对象类型,字典的值都有独立的唯一的键(Key),用相应的键来取值。
Python字典主要特性如下:
• 通过键而不是偏移量来读取
• 任意对象的无序组合
• 可变长,异构,任意嵌套
• 属于可映射类型
• 对象引用表
字典用法注意事项:
• 序列运算无效 - 串联,分片不能使用
• 对新索引(键)赋值会添加项
• 键不一定是字符串 - 只要是不可变的对象(除了列表和字典)
二、字典的操作
1、基本操作
字典的赋值(格式):
>>>dict = {'D':'Dora','E':'Emon'}#在这里'D'和'E'是键,Dora和Emon是相应的值。
取值:
>>>print("DaXiong's friend is {}{}".format(dict['D'],dict['E']))DaXiong's friend is DoraEmon
长度:
>>>len(dict)2
判断特定的键是不是存在于字典里:
>>>'D'indictTrue
列出所有的键(2.x和3.x有区别):
>>>list(dict.keys())['D','E']
2、原处修改
更改特定键的值:
>>>dict = {'D':'Dora','E':'Emon'}
>>>dict['D'] ='DaXiong'
>>>dict{'D':'DaXiong','E':'Emon'}
增加新的键和相应的值:
>>>dict['J'] ='Jing'
>>>dict{'D':'DaXiong','E':'Emon','J':'Jing'}
删除一个键:
>>>deldict['D']
>>>dict{'E':'Emon','J':'Jing'}
三、字典的方法
1、字典的取值
取所有的值:
>>>dict = {'D':'Dora','E':'Emon'}
>>>list(dict.keys())['D','E']
>>>list(dict.values())['Dora','Emon']
>>>list(dict.items())[('D','Dora'), ('E','Emon')]
不能确定某个值是不是存在的时候:
>>>dict.get('D','Not Found')#存在就输出Key对应的Values,不存在就输出自己定义的字符,这里的‘Not Found’就是自己定义的
'Dora'
>>>dict.get('Q','Not Found')
'Not Found'
2、创建字典的方法
最原始的方法:
>>>dict = {'D':'Dora','E':'Emon'}
按键赋值方法:
>>>dict = {}
>>>dict['D'] ='Dora'
>>>dict['E'] ='Emon'
变量赋值方法:
c = dict(name='Allen', age=14, gender='male')#此方法没有在我自己的电脑上尝试成功,但语法是没有问题的
元祖列表方法:
e=dict([('name','Allen'),('age',21),('gender','male')])#此方法没有在我自己的电脑上尝试成功,但语法是没有问题的
3、字典的比较
>>>Quentities = {'toast':45,'muffin':23,'ham':78,'spam':56,'eggs':89}
>>>max(Quentities)
'toast'
>>>min(Quentities)
'eggs'
我们发现,这里比较的是“键”,而不是相应的“值”,这里使用zip()函数将Quentities字典中的Key与Values顺序进行调换。
zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表),具体可以参考链接:https://blog.csdn.net/eric_sunah/article/details/20551087
>>>max(zip(Quentities.values(),Quentities.keys()))(89,'eggs')
>>>min(zip(Quentities.values(),Quentities.keys()))(23,'muffin')
>>>sorted(zip(Quentities.values(),Quentities.keys()))[(23,'muffin'), (45,'toast'), (56,'spam'), (78,'ham'), (89,'eggs')]
上面使用sorted进行排序,更改顺序只需要加reverse=True
另外一种字典比较方式:
>>>Quentities = {'toast':45,'muffin':23,'ham':78,'spam':56,'eggs':89}
>>>sorted(zip(Quentities.values(),Quentities.keys()))[(23,'muffin'), (45,'toast'), (56,'spam'), (78,'ham'), (89,'eggs')]
>>>max(Quentities,key=lambdak: Quentities[k])
'eggs'
>>>min(Quentities,key=lambdak: Quentities[k])
'muffin'
关于lambda,你可以把这个当成如下函数:
>>>defget_count(k):
...returnQuentities[k]...
>>>min(Quentities,key=get_count)
'muffin'
整体意思就是输出Key最大或最小对应的Values。
4、字典列表的排序
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}]
需要按fname或者uid排序时需要operator模块里的itemgetter函数:
>>>fromoperatorimportitemgetter
>>>rows_by_fname = sorted(rows, key=itemgetter('fname'))
>>>rows_by_uid = sorted(rows, key=itemgetter('uid'))
>>>print(rows_by_fname)[{'fname':'Big','lname':'Jones','uid':1004}, {'fname':'Brian','lname':'Jones','uid':1003}, {'fname':'David','lname':'Beazley','uid':1002}, {'fname':'John','lname':'Cleese','uid':1001}]
>>>print(rows_by_uid)[{'fname':'John','lname':'Cleese','uid':1001}, {'fname':'David','lname':'Beazley','uid':1002}, {'fname':'Brian','lname':'Jones','uid':1003}, {'fname':'Big','lname':'Jones','uid':1004}]
需要按lname和fname的顺序排列时:
>>>rows_by_lfname = sorted(rows, key=itemgetter('lname','fname'))
>>>print(rows_by_lfname)[{'lname':'Beazley','uid':1002,'fname':'David'},{'lname':'Cleese','uid':1001,'fname':'John'},{'lname':'Jones','uid':1004,'fname':'Big'},{'lname':'Jones','uid':1003,'fname':'Brian'}]
5、通过某个字段将记录分组
>>>rows = [
...{'address':'5412 N CLARK','date':'07/01/2012'},
...{'address':'5148 N CLARK','date':'07/04/2012'},
...{'address':'5800 E 58TH','date':'07/02/2012'},
...{'address':'2122 N CLARK','date':'07/03/2012'},
...{'address':'5645 N RAVENSWOOD','date':'07/02/2012'},
...{'address':'1060 W ADDISON','date':'07/02/2012'},
...{'address':'4801 N BROADWAY','date':'07/01/2012'},
...{'address':'1039 W GRANVILLE','date':'07/04/2012'},
...]
>>>fromoperatorimportitemgetter
>>>fromitertoolsimportgroupby
>>>rows.sort(key=itemgetter('date'))
>>>fordate, itemsingroupby(rows, key=itemgetter('date')):
...print(date)
...foriinitems:
...print(' ', i)
07/01/2012
{'date':'07/01/2012','address':'5412 N CLARK'}{'date':'07/01/2012','address':'4801 N BROADWAY'}
07/02/2012
{'date':'07/02/2012','address':'5800 E 58TH'}{'date':'07/02/2012','address':'5645 N RAVENSWOOD'}{'date':'07/02/2012','address':'1060 W ADDISON'}
07/03/2012
{'date':'07/03/2012','address':'2122 N CLARK'}
07/04/2012
{'date':'07/04/2012','address':'5148 N CLARK'}{'date':'07/04/2012','address':'1039 W GRANVILLE'}
领取专属 10元无门槛券
私享最新 技术干货