IronAces
IronAces

Reputation: 1883

Sorting 2D Dictionaries In Python

Very rusty with Python, and I wish to sort and print a 2D array as below. Populating 2D dictionary with studentName and studentScore. Looping around and adding new items to dictionary. I've added a studentName and studentScore as an example. I'd like to sort and print dataSet by studentName... But unsure how. Any help is appreciated as always...

dataSet = {}
position = len(dataSet)
studentName = "Derek"
studentScore = "80%"
dataSet.update({position : {"studentName": studentName, "Score": studentScore }})

I would like the output to be something like...

Student: Derek -- Score: 80%

And naturally, loop through each item in dataSet

Currently using this... But is formatted as the object and is quite ugly!

def viewScores(dataSet):
 for x in dataSet:
    for y in dataSet[x]:
        print (y,':',dataSet[x][y])

Upvotes: 0

Views: 678

Answers (3)

OBu
OBu

Reputation: 5177

You should review the usage of dictionaries in python... Your problem can be solved like this:

def viewScores(dataSet):
 for student in sorted(dataSet.keys()):
    print ("{}: {}".format(student, dataSet[student]))


dataSet = {}
studentName = "Derek"
studentScore = "80%"
dataSet[studentName] = studentScore 
dataSet["Zyline"] = "99%"

print(dataSet) # just to show it works (and it might be sorted in reverse order)

viewScores(dataSet)

Furthermore, I would recommend to store the score as number and not as string, and to add the percentage signn only in the print satement.

With your new requirement (duplicate names), I would solve it like this:

def viewScores(dataSet):
    for student in sorted(dataSet,  key=lambda x: x["studentName"]):
        print ("Student: {} -- Score {}%".format(student["studentName"], student["studentScore"]))


dataSet = []
studentID = 7
studentName = "Derek"
studentScore = 80
dataSet.append({"studentName": studentName, "studentScore": studentScore, "id": studentID}) 
dataSet.append({"studentName": "Zyline", "studentScore": 99, "id": 42})

print(dataSet) # just to show it works (and it might be sorted in reverse order)

viewScores(dataSet)

Upvotes: 1

Martin Evans
Martin Evans

Reputation: 46759

Here is another possible solution which sorts by name and then score. As suggested, it would make more sense to store your scores as integers as this would make it a bit easier to sort.

def viewScores(dataSet):
    entries = sorted([(dataSet[entry]['studentName'], dataSet[entry]['Score']) for entry in dataSet])

    for name, score in entries:
        print('Student: {} -- Score: {}%'.format(name, score))

dataSet = {}
position = len(dataSet)
studentName = "Derek"
studentScore = 80
dataSet.update({position : {"studentName": studentName, "Score": studentScore }})

position = len(dataSet)
studentName = "Andrew"
studentScore = 90

dataSet.update({position : {"studentName": studentName, "Score": studentScore }})
position = len(dataSet)
studentName = "Andrew"
studentScore = 9
dataSet.update({position : {"studentName": studentName, "Score": studentScore }})

viewScores(dataSet)

For this example it would display the following output:

Student: Andrew -- Score: 9%
Student: Andrew -- Score: 90%
Student: Derek -- Score: 80%

Upvotes: 1

Delgan
Delgan

Reputation: 19617

First, you should get values of you dictionary using .values().

Then, you can easily access studentName and studentScore for each one. I used list comprehension

Finally, sort the values using sorted().

valuesDict = dataSet.values()
valuesTuple = [(v["studentName"], v["Score"]) for v in valuesDict]
sortedValues = sorted(valuesTuple)

for student, score in sortedValues:
    print "Student: %s -- Score: %s" % (student, score)

Upvotes: 0

Related Questions