Python中對(duì)字典的幾個(gè)處理方法分享
字典求和
edge_weights = defaultdict(lambda: defaultdict(float))
for idx,node in enumerate(graph.nodes()):
node2com[node] = idx #給每一個(gè)節(jié)點(diǎn)初始化賦值一個(gè)團(tuán)id
for edge in graph[node].items():
edge_weights[node][edge[0]] = edge[1]['weight']
edge_weights運(yùn)行結(jié)果:
defaultdict(<function __main__.<lambda>()>,
{'397564': defaultdict(float,
{'15.1.18010.11898': 71,
'15.1.18010.11899': 54,
'15.1.18009.11899': 75,
'15.1.18009.11898': 160}),
'15.1.18010.11898': defaultdict(float,
{'397564': 71,
'577806': 61,
'73827465': 66,
'30009791666': 62,
'30005407392': 59,
'100293225': 102,
'30012147301': 65,
'138661946': 52}),
'1085941': defaultdict(float,
{'15.1.18007.11870': 120,
'15.1.18005.11872': 55,
'15.1.18004.11872': 75,
'15.1.18006.11870': 83,
'15.1.18004.11871': 63})
})
對(duì)上述edge_weights所有的值匯入列表并求和:
sum(
[weight for start in edge_weights.keys() for end, weight in edge_weights[start].items()]
)列表剔重并計(jì)數(shù)
方法1:
統(tǒng)計(jì)列表中的重復(fù)項(xiàng)出現(xiàn)的次數(shù)。
循環(huán)遍歷出一個(gè)可迭代對(duì)象中的元素,如果字典沒有該元素,那么就讓該元素作為字典的鍵,并將該鍵賦值為1,如果存在就將該元素對(duì)應(yīng)的值加1.
lists = ['a','a','b',5,6,7,5,'a']
count_dict = dict()
for item in lists:
if item in count_dict:
count_dict[item] += 1
else:
count_dict[item] = 1方法2:
使用collections.defaultdict(),將default_factory設(shè)為int,代碼如下:
from collections import defaultdict
#s = 'mississippi'
s = ['a','a','b',5,6,7,5,'a']
d = defaultdict(int)
for k in s:
d[k] += 1
print('\n',d)獲取字典中最大的value
a = {'a':2,'b':3,'c':5,'d':9,'e':4}
print(max(a.values()))獲取字典中出現(xiàn)value最大的key
a = {'a':2,'b':3,'c':5,'d':9,'e':4}
print(max(a,key=a.get))運(yùn)行結(jié)果:
d
字典對(duì)應(yīng)元素追加
對(duì)于列表:
s = [('yellow',1),('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]統(tǒng)計(jì)列表字典有兩種方法:
方法1:
用dict.setdefault()實(shí)現(xiàn)。
代碼如下:
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = {}
for k, v in s:
d.setdefault(k,[]).append(v)
a = sorted(d.items())
print(a)運(yùn)行結(jié)果:
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
方法2;
使用collections.defaultdict(),并使用list作第一個(gè)參數(shù),可以很容易將鍵-值對(duì)序列轉(zhuǎn)換為列表字典,
代碼如下:
from collections import defaultdict
s = [('yellow',1),('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
d[k].append(v)
a = sorted(d.items())
print(a)運(yùn)行結(jié)果:
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
當(dāng)字典中沒有的鍵第一次出現(xiàn)時(shí),default_factory自動(dòng)為其返回一個(gè)空列表,list.append()會(huì)將值添加進(jìn)新列表;再次遇到相同的鍵時(shí),list.append()將其它值再添加進(jìn)該列表。這種方法比使用dict.setdefault()更為便捷。
字典對(duì)應(yīng)元素追加并剃重
對(duì)于列表:
s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]統(tǒng)計(jì)并剃重:
from collections import defaultdict
s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
d = defaultdict(set)
for k, v in s:
d[k].add(v)
print('\n',d)運(yùn)行結(jié)果:
defaultdict(<class 'set'>, {'red': {1, 3}, 'blue': {2, 4}})
對(duì)字典進(jìn)行過濾
創(chuàng)建一個(gè)新的字典,可以利用字典推導(dǎo)式
headerTable = {k: v for k, v in headerTable.items() if v > 2}反轉(zhuǎn)字典的方法(字典的key和value對(duì)換)
使用字典推導(dǎo):
m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
{v: k for k, v in m.items()}使用壓縮器:
m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
m.items() #[('a', 1), ('c', 3), ('b', 2), ('d', 4)]
zip(m.values(), m.keys()) #[(1, 'a'), (3, 'c'), (2, 'b'), (4, 'd')]
mi = dict(zip(m.values(), m.keys()))字典的key和value對(duì)換并把key按照value進(jìn)行列表合并
對(duì)于字典:
defaultdict(int,
{'2100201919459568780': 0,
'2100201927433498080': 1,
'2100201935997972401': 2,
'2100201934073343294': 3,
'2100201938073398590': 3,
'2100201938426179130': 2,
'2100201938057211020': 4,
'2100201938030472762': 3,
'2100201940356247098': 4,
'2100201939150253460': 4,
'2100201935737728404': 4,
'2100201938984381844': 4,
'2100201937770425806': 4,
'2100201937563397283': 4,
'2100201941426286415': 4,
'2100201936062819790': 4,
'2100201936279351185': 4,
'2100201934074097553': 4,
'2100201940543713169': 4})進(jìn)行處理:
track_merge = defaultdict(list)
for i in track_label.items():
track_merge[str(i[1])].append(i[0])輸出:
defaultdict(list,
{'0': ['2100201919459568780'],
'1': ['2100201927433498080'],
'2': ['2100201935997972401', '2100201938426179130'],
'3': ['2100201934073343294',
'2100201938073398590',
'2100201938030472762'],
'4': ['2100201938057211020',
'2100201940356247098',
'2100201939150253460',
'2100201935737728404',
'2100201938984381844',
'2100201937770425806',
'2100201937563397283',
'2100201941426286415',
'2100201936062819790',
'2100201936279351185',
'2100201934074097553',
'2100201940543713169']})
合并字典
appointment = { 'soccer' : { 'day': 20, 'month': 'april' } }
appointment2 = { 'gym' : { 'day': 5, 'month': 'may' } }
appointment.update(appointment2)
appointment輸出:
{
'gym': {'day': 5, 'month': 'may'},
'soccer': {'day': 20, 'month': 'april'}
}
到此這篇關(guān)于Python中對(duì)字典的幾個(gè)處理方法分享的文章就介紹到這了,更多相關(guān)Python字典處理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
pytorch人工智能之torch.gather算子用法示例
這篇文章主要介紹了pytorch人工智能之torch.gather算子用法示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
樹莓派3 搭建 django 服務(wù)器的實(shí)例
今天小編就為大家分享一篇樹莓派3 搭建 django 服務(wù)器的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-08-08
python讀取TXT到數(shù)組及列表去重后按原來順序排序的方法
這篇文章主要介紹了python讀取TXT到數(shù)組及列表去重后按原來順序排序的方法,涉及Python操作txt文件、列表去重及排序的相關(guān)技巧,需要的朋友可以參考下2015-06-06

