9 examples of 'python sort dictionary by value descending' in Python

Every line of 'python sort dictionary by value descending' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
4def sort_by_val(input_dict, reverse = True):
5 # Returns list of key, val pairs sorted by val
6 tuples = [(key, val) for key, val in input_dict.iteritems()]
7 return sorted(tuples, key = itemgetter(1), reverse = reverse)
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

47def sort_dict(unsorted_dict):
48 return collections.OrderedDict(sorted(unsorted_dict.items(),
49 key=lambda item: item[0]))
140def sort_dict(d, sort_key='key'):
141 ordered_d = collections.OrderedDict()
142 if sort_key == 'key':
143 for key in sorted(d.keys()):
144 ordered_d[key] = d[key]
145 elif sort_key == 'value':
146 items = d.items()
147 items.sort()
148 for key, value in items:
149 ordered_d[key] = value
150 else:
151 raise TypeError(
152 'Not supported sort key:{}'.format(sort_key)
153 )
154 return ordered_d
41def sort_dict(unsorted_dict):
42 """
43 Return a OrderedDict ordered by key names from the :unsorted_dict:
44 """
45 sorted_dict = OrderedDict()
46 # sort items before inserting them into a dict
47 for key, value in sorted(unsorted_dict.items(), key=itemgetter(0)):
48 sorted_dict[key] = value
49 return sorted_dict
154def sort_dict(key_counts, by_key=False):
155 '''Accept a dict of key:values (numerics) returning list of key-value tuples ordered by desc values.
156
157 If by_key=True, sorts by dict key.'''
158 sort_key = lambda x: (-1 * x[1], x[0])
159 if by_key:
160 sort_key = lambda x: x[0]
161 return sorted(key_counts.items(), key=sort_key)
188def sort_dict(d: dict, by: str = 'key',
189 allow_duplicates: bool = True) -> collections.OrderedDict:
190 """
191 Sort a dictionary by key or value.
192
193 The function relies on
194 https://docs.python.org/3/library/collections.html#collections.OrderedDict .
195 The dulicated are determined based on
196 https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list .
197 Parameters
198 ----------
199 d : dict
200 Input dictionary
201 by : ['key','value'], optional
202 By what to sort the input dictionary
203 allow_duplicates : bool, optional
204 Flag to indicate if the duplicates are allowed.
205 Returns
206 -------
207 collections.OrderedDict
208 Sorted dictionary.
209
210 >>> sort_dict({2: 3, 1: 2, 3: 1})
211 OrderedDict([(1, 2), (2, 3), (3, 1)])
212 >>> sort_dict({2: 3, 1: 2, 3: 1}, by='value')
213 OrderedDict([(3, 1), (1, 2), (2, 3)])
214 >>> sort_dict({'2': 3, '1': 2}, by='value')
215 OrderedDict([('1', 2), ('2', 3)])
216 >>> sort_dict({2: 1, 1: 2, 3: 1}, by='value', allow_duplicates=False)
217 Traceback (most recent call last):
218 ...
219 ValueError: There are duplicates in the values: {1}
220 >>> sort_dict({1:1,2:3},by=True)
221 Traceback (most recent call last):
222 ...
223 ValueError: by can be 'key' or 'value'.
224 """
225 if by == 'key':
226 i = 0
227 elif by == 'value':
228 values = list(d.values())
229 if len(values) != len(set(values)) and not allow_duplicates:
230 duplicates = find_duplicates(values)
231 raise ValueError("There are duplicates in the values: {}".format(duplicates))
232 i = 1
233 else:
234 raise ValueError("by can be 'key' or 'value'.")
235
236 return collections.OrderedDict(sorted(d.items(), key=lambda t: t[i]))
18def sort_dict(
19 encoded_dict: Dict[str, List[Dict[str, Any]]]
20) -> Dict[str, List[Dict[str, Any]]]:
21 """
22 Helper function that sorts the value of a dict.
23 """
24 return {
25 key: sorted(value, key=lambda x: x["id"]) for key, value in encoded_dict.items()
26 }
76def order_dict(data, ordered_keys, key_map_cache={}):
77 can_cache = True
78 try:
79 key_map = key_map_cache.get(ordered_keys)
80 except TypeError:
81 key_map = None
82 can_cache = False
83 if key_map is None:
84 key_map = defaultdict(lambda: float('inf'))
85 for i, k in enumerate(ordered_keys):
86 if k not in key_map:
87 key_map[k] = i
88 if can_cache:
89 key_map_cache[ordered_keys] = key_map
90 return OrderedDict(sorted(iteritems(data), key=lambda kv: key_map[kv[0]]))
131@classmethod
132def __dict_sort(cls, dict_obj):
133 for k, v in dict_obj.items():
134 if isinstance(v, dict):
135 cls.__dict_sort(v)
136 elif isinstance(v, list):
137 cls.__list_sort(v)
138 else:
139 pass

Related snippets