saltycrane / saltycrane-blog-comments

Comments for my blog powered by utterances
https://www.saltycrane.com/blog/
0 stars 0 forks source link

blog/2007/09/how-to-sort-python-dictionary-by-keys/ #8

Open utterances-bot opened 5 years ago

utterances-bot commented 5 years ago

How to sort a Python dict (dictionary) by keys or values - SaltyCrane Blog

https://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/

rosarion commented 5 years ago

Python 3.7.2rc1 (tags/v3.7.2rc1:75a402a217, Dec 11 2018, 23:05:39) [MSC v.1916 64 bit (AMD64)] on win32

I used the following code to sort by VALUES my Dictionay print(" SORTED VALUES ## ===============================\n") for key, value in sorted(d.items(), key = lambda kv:( kv[1], kv[0])): print ("%s: %s" % (key, value))

or simply print(sorted(d.items(), key = lambda kv:( kv[1], kv[0])))

saltycrane commented 5 years ago

@rosarion (and Zoynels) thanks for the python 3 example-- I updated the post

nidaj commented 5 years ago

dict_1 = {2:56,1:2,5:12,4:24,6:18,3:323} print(dict_1)

sort by keys

for i in sorted(dict_1.keys()): print(i,":",dict_1.get(i),end=" ")

Sort By values

for i in sorted(dict_1.values(),reverse = False): for j in dict_1.keys(): if dict_1.get(j) == i: print(j,":",i)

marknathon449 commented 3 years ago

Will this code also work for Python 3? I found this new code for sort dictionary in python, is it good to work for python 3?

catchsrinivas commented 3 years ago

With the release of Python version 3.7 and above by default, dictionaries have been modified to maintain insertion order, which means now dictionaries are ordered collection of data values. Checkout the article on How to Sort Dictionary by value in Python with Python 3.7 and above