how would I go about assigning more than one value to a dictionary - rather like a list.

for example I have students who each have courses. Each student name is a key (unique)

e.g as a dictionary

student = {"name":"course"}

but students can have more than one course

student = {"name":"coursecode1", "coursecode2"} doesn't work.

I could make it a list?

student = [Joe, Jenny, Tom]
course = [MATH101, COMP202, BIO101]

but how to link the lists? i.e Joe studies MATH101 and COMP202

- how to sort a dictionary - i.e I Want to see what students COMP202 has.

This should be easy but I'm very new :(

It is very easy indeed, you can use lists of courses as values in the dictionary

# python 2

table = {
    "Joe" : [ "MATH101", "COMP202", ],
    "Jenny" : [ "COMP202", "BIO101", ],
    "Tom" : [ "MATH101", "BIO101", ],
}

print "The students in COMP202 are:",
print sorted(k for (k, v) in table.iteritems() if "COMP202" in v)

""" my output -->
The students in COMP202 are: ['Jenny', 'Joe']
"""

Maybe this is too much help, but here anyway. You could retype the keys instead of selecting from list, but it is good practice to avoid stupid typing mistakes to assure same spelling:

from pprint import pprint
students = ['Joe', 'Jenny', 'Tom']
courses = ['MATH101', 'COMP202', 'BIO101']

students_courses = {students[0]: [courses[0], courses[1]], students[1]: [courses[0], courses[2]]}
courses_students = dict((course, [participant for participant, courses_taken in students_courses.items()
                                  if course in courses_taken]) for course in courses)
pprint(students_courses)
print
pprint(courses_students)

I'm just working on your example now. But I keep getting an invalid syntax when I try to sort

same as for this simple example

knights = {'gallahad': 'the pure', 'robin': 'the brave'}
         for k, v in knights.iteritems():
         	print k, v
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
...     print k, v
...     
gallahad the pure
robin the brave

If you use python 3,then print is a function.
So it have to look like this. print(k, v) and iteritems() is items()

# Gribouillis
# python 3

table = {
    "Joe" : [ "MATH101", "COMP202", ],
    "Jenny" : [ "COMP202", "BIO101", ],
    "Tom" : [ "MATH101", "BIO101", ],
}

# print ()
print("The students in COMP202 are:", end='') #end=''
print(sorted(k for (k, v) in table.items() if "COMP202" in v)) #items()

""" my output -->
The students in COMP202 are: ['Jenny', 'Joe']
"""

thanks snippsat I spent hours trying to work that out ;p I figured it was versions but the problem is when you google for answers all of them are for older versions of python, so I kept getting errors.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.