Click here to Skip to main content
15,883,918 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
How to sort the dynamic updated dictionary data every time new keys are updated in the dictionary? It gives me a random order for the keys whenever i try to print the dictionary after updating.

mydict ={"item_0": "apples"}
print(mydict)
mydict.update(item_1="banana")
print(mydict)
mydict.update(item_2="oranges")
print(mydict)
mydict.update(item_3="peaches")
print(mydict)
mydict.update(item_4="tangerines")
print(mydict)

Actual Results
{'item_0': 'apples'}
{'item_0': 'apples', 'item_1': 'banana'}
{'item_2': 'oranges', 'item_0': 'apples', 'item_1': 'banana'}
{'item_2': 'oranges', 'item_3': 'peaches', 'item_0': 'apples', 'item_1': 
'banana'}
{'item_4': 'tangerines', 'item_2': 'oranges', 'item_3': 'peaches', 
'item_0': 'apples', 'item_1': 'banana'}

Expected Results
{'item_0': 'apples'}
{'item_0': 'apples', 'item_1': 'banana'}
{'item_0': 'apples', 'item_1': 'banana', 'item_2': 'oranges'}
{'item_0': 'apples', 'item_1': 'banana', 'item_2': 'oranges', 'item_3': 
'peaches'}
{'item_0': 'apples', 'item_1': 'banana', 'item_2': 'oranges', 'item_3': 
'peaches', 'item_4': 'tangerines'}


What I have tried:

Using Sorted function doesn't seem to work in sorting the data dynamically or atleast not returning dictionary but returns list of tuples instead. I keep getting random order whenever new keys are added to dictionary and i need to sort them and update them in JSON formatted data.
Posted
Updated 29-Jan-19 9:28am
Comments
honey the codewitch 2-Oct-20 15:33pm    
Presumably you have a reason you'd like the order preserved but the JSON spec does not guarantee the order of named items - that's what XML is for. Basically what you want is to hack the JSON protocol to meet your requirements. Not that it can't be done, but know that what you want to be doing is a hack.

1 solution

I just ran your code and got the following result:
{'item_0': 'apples'}
{'item_0': 'apples', 'item_1': 'banana'}
{'item_0': 'apples', 'item_1': 'banana', 'item_2': 'oranges'}
{'item_0': 'apples', 'item_1': 'banana', 'item_2': 'oranges', 'item_3': 'peaches'}
{'item_0': 'apples', 'item_1': 'banana', 'item_2': 'oranges', 'item_3': 'peaches', 'item_4': 'tangerines'}

I can only assume there is something in your code that you have not shown us. Although I note from the documentation:
Quote:
It is best to think of a dictionary as an unordered set of key: value pairs


See also: python sort dictionary - Google Search[^].
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900