python字典,鍵值對,但是有時候我們需要一鍵對應多個值,那麼怎麼辦呢?
例如:test.txt文件中的內容如下:
1 key1
2 key2
3 key1
7 key3
8 key2
10 key1
14 key2
19 key4
20 key1
30 key3
現在要統計,每個key包含哪些序號,這就是乙個典型的一鍵對多值。那麼使用dict.setdefault可以輕鬆解決。
d={}
def statistic(txtpath):
f=open(txtpath,'r')
for line in f.readlines():
num=line.split()[0]
key=line.split()[1]
print d
python 字典的一鍵多值
今天在寫乙個小 的時候要用到這樣的資料結構 乙個由dict 組成的list列表。可是,如何實現呢?查閱了 python cookbook 有以下三種方式 1.d1 2.d2 d2.setdefualt key,value 1 使用字典作為dict的值,自然而然的消滅了重複值的可能 3.d3 d3.s...
python 字典key值報錯
報錯 typeerror unhashable type set 或 typeerror unhashable type list 原因 python的字典型別的key不支援set或list,set裡面的物件是hash儲存,如果儲存乙個list物件,而後改變了list物件,那set中剛才儲存的值的h...
python禁止字典key排序
import collections data collections.ordereddict data b 3 data a 1 data jsonify d return make response data,200 1.正常的python dict是按字母順序排序的,所以要使用orderedd...