#一键多值字典,可列表(保留插入顺序),可合集(消除重复,无关顺序)from collections import*
a = defaultdict(list)#也可以是set,2选1
a['a1'].append(2)
a['a1'].append(2)
a['a2'].append(2)print(a)
from collections import OrderedDict
#orderedDict大小是普通字典的两倍
d = OrderedDict()#d={}(我用普通的字典怎么也是一样的哦……)#因为普通dict排序是计算 key 所在内存地址的 hash (hash是一种加密算法,可以保证唯一性)
d['a']='A'
d['b']='B'
d['c']='C'print(d)for i in d:print(i,d[i])import json
json_d = json.dumps(d)print(json_d)
example ={'x':100,'b':200,'c':300,'d':150}
min_example =min(example)#这个直接比的是key的大小
min_word =min(zip(example.values(),example.keys()))#用zip可以把key和value对调
min_word2 =min(example,key =lambda s:example[s])#得到最小值对应的keyprint(min_example,min_word,min_word2)
b (100,'x') x
#移除该序列中的重复项
a=[1,2,3,5,2,3,5,7,9,5,2]defchongfu886(list):
already =set()#set要说明,并且set可以避免重复for item inlist:if item in already:nextelse:
already.add(item)yield item
'''
简单一点的版本
if item not in alreay:
yield item
already.add(item)
'''
new_a =list(chongfu886(a))print(new_a)
a ='hfadsjoioi2938128ycnbxsj931wy8hdfoisajoiudw91jkcdshkjhf3u1hiudhsa89219034'
b='178463974678326472180931820947139864817394709317984631897409218-093812'
s=slice(10,20)
a1=a[s]
b1=b[s]
a2=a[10:20]print(a1,b1,a2)
from operator import itemgetter
a=[{'name':'a','priority':3},{'name':'b','priority':2},{'name':'c','priority':3},{'name':'d','priority':1},]#排序-itemgetter
a_by_priority =sorted(a,key=itemgetter('priority'))#也支持多个key#也可以用key = lambda s:s['priority']#但是itemgetter性能更佳#如果是不原生支持比较操作的对象,则用attrgetter#分组-groupbyfrom itertools import groupby
for priority,items in groupby(a_by_priority,key=itemgetter('priority')):print(priority)for i in items:print(' ',i)