我一直在嘗試從 CSV 檔案中獲取帶有字串元組的字典,但我遇到了麻煩。
這是我嘗試過的代碼:
fullcsv = [['Brand', 'Swap', 'Candy1', 'Candy2', 'Capacity'],
['Willywonker', 'Yes', 'bubblegum', 'mints', '7'],
['Mars-CO', 'Yes', 'chocolate', 'bubblegum', '1'],
['Nestle', 'Yes', 'bears', 'bubblegum', '2'],
['Uncle Jims', 'Yes', 'chocolate', 'bears', '5']]
def findE(fullcsv):
i = 0
a = {}
while i < len(fullcsv)-1:
i = i 1
a[i] = ({(fullcsv[i][2],fullcsv[i][3]): int(fullcsv[i][4])})
return a
這是這段代碼的輸出:
{1: {('bubblegum', 'mints'): 7},
2: {('chocolate', 'bubblegum'): 1},
3: {('bears', 'bubblegum'): 2},
4: {('chocolate', 'bears'): 5}}
但我正在尋找的輸出更像是這樣的:
{('bubblegum', 'mints'): 7,
('chocolate', 'bubblegum'): 1,
('bears', 'bubblegum'): 2,
('chocolate', 'bears'): 5}
這樣元組就沒有編號,也不是在他們自己的{},而只是在括號中()。
uj5u.com熱心網友回復:
如果你愿意,這里有一個稍微不同的方法。
def findE(fullcsv):
new_dict = {}
for entry in fullcsv[1:]:
new_dict[(entry[2],entry[3])] = entry[-1]
return new_dict
uj5u.com熱心網友回復:
在函式中,您需要像這樣設定字典的鍵值對
a[(fullcsv[i][2],fullcsv[i][3])] = int(fullcsv[i][4])
所以完整的功能是
def findE(fullcsv):
i = 0
a ={}
while i < len(fullcsv)-1:
i = i 1
a[(fullcsv[i][2],fullcsv[i][3])] = int(fullcsv[i][4])
return a
一般語法是
dictionary[new_key] = new_value
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/471977.html
下一篇:遍歷字典中的串列
