To sort a dictionary on the item value you can use
sorted(d, key=d.__getitem__)
In your case the code becomes
for k in sorted(d, key=d.__getitem__, reverse=True):
print(k + d[k] + "hi")
Explanation
When in Python you write
d[k]
what is evaluated is
d.__getitem__(k)
so d.__getitem__
when d
is a dictionary is a function that given a key returns the value associated to that key in the dictionary.
sorted
instead is a predefined function that returns a sorted version of a sequence and accepts an optional parameter (named somewhat unfortunately key
, but note that key has no relation to dictionaries here). This parameter can be used to determine on what the ordering comparison should be done; sorted
also supports another optional parameter reversed
where you can determine if ascendant or descendant sorting is required.
Finally when a dictionary is used as a sequence (for example passing it to sorted
or iterating over it in a for
) what you obtain are the keys of the dictionary.
This for example implies that sorted(d, key=d.__getitem__)
returns the keys of the dictionary sorted according the value.