-2
# Sort the elements in dictionary based on its values
# without adding duplicates

dict1 = **{1:1, 2:9, 3:4, 4:6}**

sorted_values = sorted(dict1.values()) # Sort the values

sorted_dict = {}

for i in sorted_values:

    for k in dict1.keys():
        if dict1[k] == i:
            sorted_dict[k] = dict1[k]
            break

print(sorted_dict)

Output : **{1: 1, 3: 4, 4: 6, 2: 9}**

# with adding duplicates

# Sort the elements in dictionary based on its values

dict1 = **{0:6, 1:1, 2:9, 3:4, 4:6}**

sorted_values = sorted(dict1.values()) # Sort the values

sorted_dict = {}

for i in sorted_values:

    for k in dict1.keys():
        if dict1[k] == i:
            sorted_dict[k] = dict1[k]
            break

print(sorted_dict)

Output :

{1: 1, 3: 4, 0: 6, 2: 9}

here 4:6 is not printing I have to print all values from dictionary even there are duplicates in a dictionary

buran
  • 13,682
  • 10
  • 36
  • 61

2 Answers2

1

What you do is terribly inefficient because you use 2 nested loops: an outer one on the values, then an inner one on the keys of the whole dictionary. It would be both simpler and most efficient to directly process the dictionary items and sort them according to the value:

sorted_items = sorted(dict1.items(), key=lambda x: x[1])
sorted_dict = dict(sorted_items)

with you 2nd example, it gives as expected:

{1: 1, 3: 4, 0: 6, 4: 6, 2: 9}
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

You can consider using an ordered dict for this.

>>> import operator
>>> from collections import OrderedDict
>>> dict1 = {1:1, 2:9, 3:4, 4:6}
>>> sorted_dict1 = sorted(dict1.items(), key=operator.itemgetter(1))
>>> dict2 = (OrderedDict(sorted_dict1))
>>> print(dict2)
OrderedDict([(1, 1), (3, 4), (4, 6), (2, 9)])

However, to have order and duplicates at the same time, tuples are a better solution.

Vijayendar Gururaja
  • 752
  • 1
  • 9
  • 16
  • dict are `insertion ordered` so creating a new one is not necessary to use OrderedDict https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6 – Glauco Dec 06 '21 at 11:12