Reputation: 1942
I want to sort the following dictionary by the keys score
, which is an array.
student = {"name" : [["Peter"], ["May"], ["Sharon"]],
"score" : [[1,5,3], [3,2,6], [5,9,2]]}
For a better representation:
Peter ---- [1,5,3]
May ---- [3,2,6]
Sharon ---- [5,9,2]
Here I want to use the second element of score
to sort the name
into a list.
The expected result is:
name_list = ("May ", "Peter", "Sharon")
I have tried to use
sorted_x = sorted(student.items(), key=operator.itemgetter(1))
and
for x in sorted(student, key=lambda k: k['score'][1]):
name_list.append(x['name'])
but both dont work.
Upvotes: 0
Views: 103
Reputation: 679
If you want to use dictionaries, I suggest using OrderedDict
:
name = ["Peter", "May", "Sharon"]
score = [[1,5,3], [3,2,6], [5,9,2]]
d = {n: s for (n, s) in zip(name, score)}
from collections import OrderedDict
ordered = OrderedDict(sorted(d.items(), key=lambda t: t[1][1]))
list(ordered) # to retrieve the names
But, if not, the following would be a simpler approach:
name = ["Peter", "May", "Sharon"]
score = [[1,5,3], [3,2,6], [5,9,2]]
d = [(n, s) for (n, s) in zip(name, score)]
ordered = sorted(d, key=lambda t: t[1][1])
names_ordered = [item[0] for item in ordered]
Upvotes: 1
Reputation: 18645
This would probably work for you:
student = {
"name": [["Peter"], ["May"], ["Sharon"]],
"score": [[1,5,3], [3,2,6], [5,9,2]]
}
# pair up the names and scores
# this gives one tuple for each student:
# the first item is their name as a 1-item list
# the second item is their list of scores
pairs = zip(student['name'], student['score'])
# sort the tuples by the second score:
pairs_sorted = sorted(
pairs,
key=lambda t: t[1][1]
)
# get the names, in order
names = [n[0] for n, s in pairs_sorted]
print names
# ['May', 'Peter', 'Sharon']
Upvotes: 1
Reputation: 164
First zip the students name and score use zip
.
zip(student["name"], student["score"])
you will get better representation:
[(['May'], [3, 2, 6]),
(['Peter'], [1, 5, 3]),
(['Sharon'], [5, 9, 2])]
then sort this list and get the student name:
In [10]: [ i[0][0] for i in sorted(zip(student["name"], student["score"]), key=lambda x: x[1][1])]
Out[10]: ['May', 'Peter', 'Sharon']
Know about the sorted buildin function first: https://docs.python.org/2/howto/sorting.html#sortinghowto
Upvotes: 3