How to make a dictionary retain its sort order?

2024/10/11 0:26:35
def positive(self):total = {}final = {}for word in envir:for i in self.lst:if word in i:if word in total:total[word] += 1else:total[word] = 1final = sorted(total, reverse = True)return total

This returns

{'climate': 10, 'ecosystem': 1, 'energy': 6, 'human': 1, 'world': 2, 'renewable': 2, 'native': 2}

I want to get this dictionary back to a dictionary that is in order. How do you I sort it and return a dictionary?

Answer

An ordered dictionary would get you what you need

from collections import OrderedDict

If you want to order your items in lexicographic order, then do the following

d1 = {'climate': 10, 'ecosystem': 1, 'energy': 6, 'human': 1, 'world': 2, 'renewable': 2, 'native': 2}
od = OrderedDict(sorted(d1.items(), key=lambda t: t[0]))

Contents of od:

OrderedDict([('climate', 10),('ecosystem', 1),('energy', 6),('human', 1),('native', 2),('renewable', 2),('world', 2)])

If you want to specify exactly which order you want your dictionary, then store them as tuples and store them in that order.

t1 = [('climate',10), ('ecosystem', 1), ('energy',6), ('human', 1), ('world', 2), ('renewable', 2), ('native', 2)]
od = OrderedDict()for (key, value) in t1:od[key] = value 

od is now

OrderedDict([('climate', 10),('ecosystem', 1),('energy', 6),('human', 1),('world', 2),('renewable', 2),('native', 2)])

In use, it is just like a normal dictionary, but with its internal contents' order specified.

https://en.xdnf.cn/q/118390.html

Related Q&A

Counting line frequencies and producing output files

With a textfile like this:a;b b;a c;d d;c e;a f;g h;b b;f b;f c;g a;b d;fHow can one read it, and produce two output text files: one keeping only the lines representing the most often occurring couple …

Check if parent dict is not empty and retrieve the value of the nested dict

Lets suppose that I have a nested dictionary which looks like that:parent_dict = { parent_key: {child_key: child_value}How can I write the following code:if parent_dict.get(parent_key) is not None and …

List combinations in defined range

I am writing parallel rainbow tables generator using parallel python and multiple machines. So far, I have it working on a single machine. It creates all possible passwords, hashes them, saves to file.…

Python turtle drawing a symbol

import turtlewin=turtle.Screen()t = turtle.Turtle() t.width(5)#The vertical and horizontal lines t.left(90) t.forward(70) t.left(90) t.forward(20)t.left(90) t.forward(60) t.left(120) t.forward(35) t.b…

Display a countdown for the python sleep function in discord embed in python

hi all I am doing one discord bot I need to send one countdown its like a cooldown embed after every request I did this code but I dont know how to add this in my embedfor i in range(60,0,-1):print(f&q…

Bypass rate limit for requests.get

I want to constantly scrape a website - once every 3-5 seconds withrequests.get(http://www.example.com, headers=headers2, timeout=35).json()But the example website has a rate limit and I want to bypass…

ValueError when using if commands in function

Im creating some functions that I can call use keywords to call out specific functions,import scipy.integrate as integrate import numpy as npdef HubbleParam(a, model = "None"):if model == &qu…

Python consecutive subprocess calls with adb

I am trying to make a python script to check the contents of a database via adb. The thing is that in my code,only the first subprocess.call() is executed and the rest are ignored. Since i am fairly ne…

Django Page not found(404) error (Library not found)

This is my music\urls.py code:-#/music/ url(r^/$, views.index, name=index),#/music/712/ url(r^(?P<album_id>[0-9]+)/$, views.detail, name=detail),And this is my views.py code:-def index(request):…

Django. Create object ManyToManyField error

I am trying to write tests for my models.I try to create object like this:GiftEn.objects.create(gift_id=1,name="GiftEn",description="GiftEn description",short_description="Gift…