I have a dictionary in Python, for example: dict = {'a': 1, 'q': 1, 'l': 2, 'm': 1, 'u': 1, 'i': 1}
Is there any way to preserve the order of this dictionary this way. I have already read several forums, and most of them suggest using OrderedDict (). But as explained here:
Python OrderedDict does not support element order
OrderedDict (dict) will not preserve order when the dictionary is written in this form. I cannot manually create a dictionary in a certain way (for example, a list of tuples), because it is accidentally generated by code in another place. Thank you so much for your help!
, dict = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1}, . :
dict = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1}
. OrderedDict .
OrderedDict
. dict , OrderedDict .
dict
, , . " ", , - , , OrderedDict, . - , dict , , , , , , .
PS dict dict.
, , , , key:value :
key:value
pairs = my_dict.items()
. , OrderedDict
from collections import OrderedDict # sort in some way (for example, reverse the key order) pairs = reversed(my_dict.items()) ordered = OrderedDict(pairs)
Just use 2 for:
dict = {'a':4, 'q':1, 'l':2, 'm':4, 'p':1} i = max(dict.values())+1 for el in range (i): for letter in dict: if el==dict[letter]: print(letter,dict[letter])
Source: https://habr.com/ru/post/1531675/More articles:Setting defaults in select2 using an AJAX call? - javascriptorg.codehaus.jackson.map.JsonMappingException: Unable to deserialize java.util.ArrayList instance from START_OBJECT token - hibernateLaravel helper function base_path () not working - phpClientRequestFactory RestEasy Deprecated ... Any other alternative to RestEasy? - javaОбновление управления из вторичного потока: критически критично? - multithreadingglReadPixels gives black image only on iOS 7 device - iphoneUnable to get hidden image to display with .show () - javascriptLaravel @foreach - invalid argument entered - phpIs the constructor "called" against the constructor "executing"? - javazsh error: export: 54: invalid in this context: - shellAll Articles