嘗試創建一個函數來讀取文件並將其添加到一個有組織的字典中,然後在不更改原始字典的情況下返回它。不知道我是否正確使用多個項目和值。功能:讀取文件,然後將多個項目添加到字典
返回:
{'Leonardo da Vinci': [("Portrait of Isabella d'Este", 1499, 63.0, 46.0, 'chalk', 'France'), ('The Last Supper', 1495, 460.0, 880.0, 'tempera', 'Italy')], 'Pablo Picasso': [('Guernica', 1937, 349.0, 776.0, 'oil paint', 'Spain')]}
示例文件:
file1='''"Artist","Title","Year","Total Height","Total Width","Media","Country"
"Pablo Picasso","Guernica","1937","349.0","776.0","oil paint","Spain"
"Leonardo da Vinci","The Last Supper","1495","460.0","880.0","tempera","Italy"'''
代碼我到目前爲止有:
def add_work (db,artist,title,year,height,width,media,country):
db = {}
with open(filename) as f:
for line in f:
(title, year, height, width, media, country) = line.split()
db[int(artist)] = (title, year, height, width, media, country)
for i in d.keys():
if i == artist #If artist in dictionary, then add it to item.
db[i].extend
elif i == title #If it has the same title as in the database, its a duplicate so return none.
return None
add_work(d1,"Leonardo da Vinci","Portrait of Isabella d'Este", 1499, 63.0,46.0, "chalk", "France")
限制:
符號順序:按ASCII碼 排序,而不是按字母順序排列。
沒有導入/集合/模塊。基本建立在函數,循環和字典方法。
「ASCII整理順序」和「字母順序」有什麼區別?你的意思是所有大寫字母都寫在所有小寫字母之前嗎?或者這涉及到非字母字符?或兩者? –
是的@RoryDaulton所有大寫字母都出現在所有小寫字母之前。不涉及非字母字符 –
我並沒有真正明白你想要做什麼,但是'db [int(artist)] = ...'應該引發'ValueError',因爲藝術家的名字贏了不是一個整數 - 請嘗試澄清你想要做的是什麼。您是否正在讀取csv-File中的數據並將藝術家的所有繪畫作爲列表中的元素進行關聯? – Maurice