在Python中合并三个词典

时间:2016-11-09 14:32:47

标签: python dictionary

我正在尝试将三个词典合并在一起。

我收到unsupported operand types错误。

这是我的代码:

def add_student():
    global Snumber
    global iCode
    global kCode
    Snumber = Student_number.get()
    Sname = Student_name.get()
    Ssurnname = Student_surname.get()
    Sdetail = Student_detail.get()
    i = Students(Snumber,Sname,Ssurnname,Sdetail)
    Sinfo[Snumber]=[Sname,Ssurnname,Sdetail]

   iName = Student_subject.get()
   iCode = Student_code.get()
   iMark1 = Student_Mark1.get()
   iMark2 = Student_Mark2.get()
   iMark3 = Student_Mark3.get()
   iProject = Student_project.get()
   j = Subjects(iName,iCode,iMark1,iMark2,iMark3,iProject)
   SSubject[iCode]=[iName,iMark1,iMark2,iMark3,iProject]

  kCourse = Degree_course.get()
  kCode = Degree_code.get()
  kYear = Degree_year.get()
  v = Degrees(kCourse,kCode,kYear)
  SDegree[kCode]=[kCourse,kYear]

  popup_add()
  student_list = (Sinfo.items() + SSubject.items() + SDegree.items())
  print(student_list)

我相信我的问题在于:

  student_list = (Sinfo.items() + SSubject.items() + SDegree.items())
  print(student_list)

2 个答案:

答案 0 :(得分:0)

你可以使用dict.update()

>>> a = {1:1,2:2,3:3}
>>> a
{1: 1, 2: 2, 3: 3}
>>> b = {4:4,5:5}
>>> c = {6:6,7:7}
>>> a.update(b)
>>> a.update(c)
>>> a
{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7}

如果您不想修改原件,可以使用以下内容将其复制到新变量

>>> new_dict = dict(a)

答案 1 :(得分:0)

要合并多个字典,假设我们有字典Sinfo,SSubject和SDegree

student_list = dict(Sinfo.items() + SSubject.items() + SDegree.items())

但根据你提到的不支持的操作数类型错误,看起来你还有其他问题的Sinfo,SSubject和SDegree dict没有足够的信息来评论