我有一個這種格式的檔案:
name x y clas
x1 1 1 A
x2 2 2 B
x3 3 3 B
x4 4 4 C
x5 5 5 D
并試圖創建一個基于它的clas鍵和組的字典name:
#Just reading reading the file in
data = {}
with open('sample.csv') as file:
next(file)
reads = file.readlines()
for lines in reads:
line = lines.strip('\n').lower()
(name, x, y, clas) = line.split(",")
data[name] = x,y,clas
#How to assign "array" values based on their "clas"
dictionary = {}
array = ['x1', 'x2', 'x3', 'x4', 'x5']
for i in range(len(array)):
classs = data.get(array[i])[2]
dictionary[classs] = [array[i]]
print(dictionary)
該函式應輸出一個字典,其中“類”作為具有相應“名稱”值的鍵。
但是,目前的輸出{'a': ['x1'], 'b': ['x3'], 'c': ['x4'], 'd': ['x5']}確實包含具有相同鍵的“名稱”值。
不確定要撰寫什么條件才能正確輸出字典,那么有沒有辦法使輸出{'a': ['x1'], 'b': ['x2','x3'], 'c': ['x4'], 'd': ['x5']}僅使用默認的 Python 函式?...
uj5u.com熱心網友回復:
使用defaultdict帶有list值的 & 附加到它而不是覆寫。
dictionary = defaultdict(list)
array = ['x1', 'x2', 'x3', 'x4', 'x5']
for i in range(len(array)):
classs = data.get(array[i])[2]
dictionary[classs].append(array[i])
print(dictionary)
uj5u.com熱心網友回復:
嗯,我設法得到了預期的結果:
dictionary = {}
for key, value in sorted(data.items()):
dictionary.setdefault(value[2], []).append(key)
print(dictionary)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/328534.html
