字典构造、合并(dict)、排序
使用dict,zip方法将两个list合并为dict keys = ["b", "a", "c", "e", "d"] values = ["2", "1", "3", "5", "4"] dict(zip(keys, values)) #该dict是无序的 d=dict(zip(keys, values)) [(k,d[k]) for k in sorted(d.keys())] #按keys排序,升序 [(k,d[k]) for k in sorted(d.keys(),reverse=True)] #按keys排序,降序
按value排序:
dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0} dict= sorted(dic.iteritems(), key=lambda d:d[1], reverse = True) print dict
dict()函数将包含有多个元组的list可以转换为字典:
y=[('name','zhangsan'),('age',20)] print dict(y) #返回{'age': 20, 'name': 'zhangsan'}
将两个字典f1、f2合并,重复项的value相加,非重复项保留:
注:只能对数字格式的value值进行相加
print f1 #返回{'10.160.31.31': 44, '10.160.100.3': 46, '10.160.100.2': 47, '::1': 92, '10.160.100.241': 8017, '127.0.0.1': 36} print f2 #返回{'106.185.41.148': 1, '10.160.31.31': 36, '10.160.100.3': 44, '10.160.100.2': 44, '::1': 39, '111.201.171.47': 1, '10.160.100.241': 8005, '127.0.0.1': 47} from collections import Counter print dict(Counter(f1) + Counter(f2)) #返回{'106.185.41.148': 1, '10.160.31.31': 80, '10.160.100.3': 90, '10.160.100.2': 91, '::1': 131, '111.201.171.47': 1, '10.160.100.241': 16022, '127.0.0.1': 83}
字典合并,两个字典中的key不能重复,否则会被后一个字典覆盖掉:
d1={'k1':['abc'],'k2':'m'} d2={'k11':['a'],'k22':'n'} d3 = dict(d1,**d2) print d3 #返回:{'k22': 'n', 'k2': 'm', 'k1': ['abc'], 'k11': ['a']} #等同于如下: # d3 = d1.copy() # d3.update(d2) #print d3
字典合并,value值为list的可以进行重复合并:
d1={'k1':['abc'],'k2':['m']} d2={'k1':['a'],'k22':['n']} d3= {} for k,v in (d1.items() + d2.items()): if d3.get(k) is None: d3[k] = v else: d3[k].extend(v) print d3 #返回:{'k22': ['n'], 'k2': ['m'], 'k1': ['abc', 'a']}
将字符串的dict转换为json格式:
udata = ‘{‘a’:'aa','b':'bbb'}’ #udata是string
from ast import literal_eval
udataj = literal_eval(udata) #udataj是dict