2016-07-08 33 views
0

我简化了我的代码来说明我正在尝试做什么。我有一些东西的列表,并且在那个列表中也是我对字典的关键。我试图做一个for循环,它接受列表中的每个元素,在该元素上运行一个函数,然后我想用函数返回的内容来扩展我的字典。我在这里做错了什么?我想通过列表扩展一个现有的词典for循环通过列表

student_list = ['Whitney', 'Jason'] 
first_dict = {'Whitney':'Math', "Jason":"Biology"} 

def schedule(student): 
    B = 'Science' 
    C = 'Social Studies' 
    D = 'Gym' 
    E = 'Lunch' 

for student in student_list: 
    schedule(student) 
    first_dict[student].append([B, C, D, E]) 

我的错误是:'str' object has no attribute 'append'

虽然我知道我在做别的事情是错误的。

回答

1

您正试图将您的值追加到字符串,这是你不能做的事情。将first_dict中的值从字符串更改为列表(例如'Math'['Math']),您的问题将得到解决。

+0

谢谢!我也将.append移到了函数中,而不是for循环中,但我最终得到了这个结果:''''''''''''''''''''科学'''社会研究''健身房'午餐']],'惠特尼':['数学',['科学','社会研究','健身房','午餐]]}''。有没有办法让数学和所有其他科目都在同一个名单中? – WhitneyChia

+0

另外,您应该在方法'schedule“外定义变量'B','C','D'和'E'。因为现在只有'schedule'方法是本地的。 – ifvictr

0

尝试类似这样的事情。

student_list = ['Whitney', 'Jason'] 
first_dict = {'Whitney':['Math'], "Jason":["Biology"]} 

def schedule(student): 
    B = 'Science' 
    C = 'Social Studies' 
    D = 'Gym' 
    E = 'Lunch' 
    first_dict[student].extend([B, C, D, E]) 

for student in student_list: 
    schedule(student)