+ 1
How to sort this dictionary?
I need to sort this dictionary in this program by values but it is not working. https://code.sololearn.com/coMZ7ek4kBvO/?ref=app
5 odpowiedzi
+ 6
A dict can be sorted by using a dict comprehension like this:
am={"a":2,"b":1,"c":3}
print({key: value for key, value in sorted(am.items(), key=lambda x: x[1],reverse=True)})
#output is {'c': 3, 'a': 2, 'b': 1}
+ 3
You can not directly sort a dictionary, you can only create a new dictionary from a sorted iterable.
print(
{
x: dict[x]
for x in sorted(
dict,
key=lambda x: dict[x],
reverse=True
)
}
)
+ 2
Since it's probably not needed to reshape the whole dict if it's only for output, I would btw probably do something like this:
width = len(
max(dict, key=lambda x: len(x))
)
for key in sorted(
dict,
key = lambda x: dict[x],
reverse = True
):
print(key.ljust(width), dict[key])