I like this one:
sorted(d, key=d.get)
Answer from dF. on Stack Overflowpairs= [(1,'one'),(2,'two'),(3,'three'),(4,"four"),(5,"five")] pairs.sort(key=lambda pair: pair[1]) >>> pairs [(5, 'five'), (4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
why is it sorted like that I didn't understand? Why can't I write a number greater than 1 in pair[1]?
How to sort a dictionary where keys have multiple values?
Use a lambda as your sort function.
# lambda r: r[1][2]
# r == ('John Adams', ('111223333', 'A', 91.0))
# r[1] == ('111223333', 'A', 91.0)
# r[1][2] == 91.0
#
d = {
'John Adams': ('111223333', 'A', 91.0),
'Willy Smith Jr.': ('222114444', 'C', 77.55),
'Phil Jordan': ('777886666', 'F', 59.5)
}
for key, value in sorted(d.items(), key=lambda r: r[1][2]):
print(key, value)Produces:
('Phil Jordan', ('777886666', 'F', 59.5))
('Willy Smith Jr.', ('222114444', 'C', 77.55))
('John Adams', ('111223333', 'A', 91.0))
By the way, if you end up with multiple entries sharing the same sort value, you can build a compound sort (secondary, tertiary, etc). Your lambda should just return a tuple: lambda r: (r[1][2], r[0]), which would sort by that last value, and then by name if multiple values equal each other.
Here's without lambda:
def key_func(key_value_tuple):
name = key_value_tuple[0]
long_str_num, a_to_f, number = key_value_tuple[1]
return (number, name)
d = {
'John Adams': ('111223333', 'A', 91.0),
'Willy Smith Jr.': ('222114444', 'C', 77.55),
'Phil Jordan': ('777886666', 'F', 59.5)
}
for key, value in sorted(d.items(), key=key_func):
print(key, value)Edit: Added non-lambda option.
More on reddit.comSorting dictionary by key with lambda: WTF??
sorting - How to sort a Python dictionary by value? - Stack Overflow
sorting with key=lambda
Videos
So say this is my dictionary: {'John Adams': ('111223333', 'A', 91.0), 'Willy Smith Jr.': ('222114444', 'C', 77.55), 'Phil Jordan': ('777886666', 'F', 59.5)} and i want to sort it by the third value of each key (eg the 91.0 for John Adams). How would I go about doing that?
Use a lambda as your sort function.
# lambda r: r[1][2]
# r == ('John Adams', ('111223333', 'A', 91.0))
# r[1] == ('111223333', 'A', 91.0)
# r[1][2] == 91.0
#
d = {
'John Adams': ('111223333', 'A', 91.0),
'Willy Smith Jr.': ('222114444', 'C', 77.55),
'Phil Jordan': ('777886666', 'F', 59.5)
}
for key, value in sorted(d.items(), key=lambda r: r[1][2]):
print(key, value)
Produces:
('Phil Jordan', ('777886666', 'F', 59.5))
('Willy Smith Jr.', ('222114444', 'C', 77.55))
('John Adams', ('111223333', 'A', 91.0))
By the way, if you end up with multiple entries sharing the same sort value, you can build a compound sort (secondary, tertiary, etc). Your lambda should just return a tuple: lambda r: (r[1][2], r[0]), which would sort by that last value, and then by name if multiple values equal each other.
Here's without lambda:
def key_func(key_value_tuple):
name = key_value_tuple[0]
long_str_num, a_to_f, number = key_value_tuple[1]
return (number, name)
d = {
'John Adams': ('111223333', 'A', 91.0),
'Willy Smith Jr.': ('222114444', 'C', 77.55),
'Phil Jordan': ('777886666', 'F', 59.5)
}
for key, value in sorted(d.items(), key=key_func):
print(key, value)
Edit: Added non-lambda option.
Here's an extension of u/totallygeek's non-lambda solution, using a more advanced Python feature:
d = {'John Adams': ('111223333', 'A', 91.0), 'Willy Smith Jr.': ('222114444', 'C', 77.55),
'Phil Jordan': ('777886666', 'F', 59.5)}
def sortindex(index):
def key_func(item):
key, value = item
return (value[index], key)
return key_func
for key, value in sorted(d.items(), key=sortindex(2)):
print(key, value)
Here, key_func is wrapped inside another function, sortindex, which returns key_func. In other words, the code above does the same thing as this
def key_func(item):
key, value = item
return (value[2], key)
for key, value in sorted(d.items(), key=key_func):
print(key, value)
But notice that the sortindex function allows us to keep the tuple index as a free variable, so that we can also sort on sortindex(0) or sortindex(1).
This technique of wrapping one function inside another is called a closure.
Hi,
going through the python.org tutorial. Came across this example:
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] >>> pairs.sort(key=lambda pair: pair[1]) >>> pairs [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
Ran it through pythontutor, and what i can see is that
the lambda function returns the second element of each tuple.
the dictionary is then sorted by order of these elements('one','two', etc)
what I dont understand, is the function of the pair variable, and the key variable. pair i'm assuming is a placeholder necessary for the lambda function to return that value.
But is key a python keyword to be interpreted as the keys to the dictionary values, or is that an arbitrary variable used to make the lambda function work as well?
Dictionaries can't be sorted as such, but you can sort their contents:
sorted(a_dict.items(), key=lambda (k, (v1, v2)): v2)
sorted(a_dict.items(), key=lambda item: item[1][1]) # Python 3
You can put the results into a collections.OrderedDict (since 2.7):
OrderedDict(sorted(a_dict.items(), key=lambda (k, (v1, v2)): v2))
OrderedDict(sorted(a_dict.items(), key=lambda item: item[1][1]) # Python 3
In your example you are using list of dictionaries. Sorting the dict by key:
mydict = {'carl':40,
'alan':2,
'bob':1,
'danny':3}
for key in sorted(mydict.iterkeys()):
print "%s: %s" % (key, mydict[key])
alan: 2
bob: 1
carl: 40
danny: 3
If you want to sort a dict by values, please see How do I sort a dictionary by value?