Python 附加到字典内的列表会删除以前的值
所以我想要一个函数,在这个函数中,我读取一个文件,并用每个“配方”创建一个实例。我还想创建一个字典,其中包含另一个指向列表的双生词。这是我的目标格式:Python 附加到字典内的列表会删除以前的值,python,python-3.x,list,dictionary,Python,Python 3.x,List,Dictionary,所以我想要一个函数,在这个函数中,我读取一个文件,并用每个“配方”创建一个实例。我还想创建一个字典,其中包含另一个指向列表的双生词。这是我的目标格式: {cuisine:{course:[recipe_instance...]...}...} 但是当我运行下面的版本时,我在每个列表中只得到一个项目,尽管每个列表中有多个项目。我假设我正在覆盖以前的值,但我正在将其附加到列表中,因此我不确定这是否正确。任何帮助都有帮助 def read_file(filename): with open(
{cuisine:{course:[recipe_instance...]...}...}
但是当我运行下面的版本时,我在每个列表中只得到一个项目,尽管每个列表中有多个项目。我假设我正在覆盖以前的值,但我正在将其附加到列表中,因此我不确定这是否正确。任何帮助都有帮助
def read_file(filename):
with open(filename,"r", encoding='utf-8') as filein:
filein.readline()
reader = csv.reader(filein)
dic = {}
for line in reader:
srno = line[0]
recipe_name = line[1]
translated_recipe_name = line[2]
ingredients = line[3]
translated_ingredients = line[4]
prep_time = line[5]
cook_time = line[6]
total_time = line[7]
servings = line[8]
cuisine = line[9]
course = line[10]
diet = line[11]
translated_instructions = line[13]
url = line[14]
every_recipe = r.Recipe(srno, translated_recipe_name, translated_ingredients, prep_time,
cook_time, total_time, servings, cuisine, course, diet, translated_instructions, url)
if cuisine not in dic:
dic[cuisine] = {course:[every_recipe]}
elif cuisine in dic:
if course not in cuisine:
dic[cuisine][course] = [every_recipe]
elif course in cuisine:
course.append(every_recipe)
return dic
课程
不是字符串吗?您如何调用.append
?看起来你想要dic[烹饪][课程]。追加(每个食谱)
。如果课程不在dic[烹饪]中,我想你需要:
和elif课程在dic[烹饪]:
和dic[烹饪][课程]。追加(每个食谱)