user3369770
user3369770

Reputation: 11

Matching 2 lists

I am trying to match a students name to the the score they got in a test. So I have 2 lists

year3studentslist = ['Dave','Tom','Alan']
year3scorelist = ['17','3','12']

What happens in my programme is the student logs in completes the test and gets a score. How would I go about matching the name of the student to the score?

Upvotes: 1

Views: 108

Answers (3)

shaktimaan
shaktimaan

Reputation: 12092

Using zip() is probably the simplest way to do it. Doing zip(year3studentslist, year3scorelist) returns a list of tuples as:

[('Dave', '17'), ('Tom', '3'), ('Alan', '12')]

So just iterate over this list to access the elements:

for student, score in zip(year3studentslist, year3scorelist):
    print student, score

If you want to access the data by name of the student, you could convert the above zipped data into a dictionary as:

data_dict = {item[0]: item[1] for item in zip(year3studentslist, year3scorelist)}

which is the same as

data_dict = dict(zip(year3studentslist, year3scorelist))

Now you can access 'Dave's' score as data_dict['Dave']. But note that, in a dictionary the keys must be unique. In this case, we chose the name of the student to be the key which is not a good idea in the case where there be two Dave's in a class. It is a good idea to use the dictionary approach only when you are assured the names will be unique

Upvotes: 6

A.J. Uppal
A.J. Uppal

Reputation: 19264

You can use a map or dict object:

year3studentslist = ['Dave','Tom','Alan']
year3scorelist = ['17','3','12']
students = {}
for k in range(len(year3studentslist)):
    students[year3studentslist[k]] = year3scorelist[k]

print students
#{'Dave': '17', 'Alan': '12', 'Tom': '3'}

Upvotes: 0

Raydel Miranda
Raydel Miranda

Reputation: 14360

Use python dicts.

Using dictionary is a better approach to what you want to do.

>>> Students = {}
>>> Student['Dave'] = 17  # Create the record for Dave
>>> Student['Tom'] = 3    # Create the record for Tom
>>> Student['Alan'] = 17  # Create the record for Alan
>>> Student['Dave'] = 15  # Update record for Dave


>>> print(Students['Dave'])
>>> 15

Y you want to obtaing the scores or the student's names separately you can:

>>> Students.keys()
>>> ['Dave', 'Tom', 'Alan']
>>> Students.values()
>>> [15, 3, 17]

Upvotes: 0

Related Questions