Sort a dictionary of dictionaries python

2024/10/13 10:27:17

I have a dictionary of dictionaries like the following

d = {'hain': {'facet': 1, 'wrapp': 1, 'chinoiserie': 1}, 'library': {'sconc': 1, 'floor': 1, 'wall': 2, 'lamp': 6, 'desk': 1, 'table': 1, 'maine': 1} 
}

So, I want to reverse sort this dictionary based on the ultimate value:

so what I am expecting is to print out something like this:

  key_1,   key_2 , valuelibrary   lamp      6library   wall      2

and so on...

How do i get this?

Thanks

Answer

Here is how you could get the sorted list you are looking for:

items = ((k, k2, v) for k in d for k2, v in d[k].items())
ordered = sorted(items, key=lambda x: x[-1], reverse=True)

This first converts your dictionary into a generator that yields the tuples (key_1, key_2, value), and then sorts this based on the value. The reverse=True makes it sort highest to lowest.

Here is the result:

>>> pprint.pprint(ordered)
[('library', 'lamp', 6),('library', 'wall', 2),('hain', 'facet', 1),('hain', 'wrapp', 1),('hain', 'chinoiserie', 1),('library', 'sconc', 1),('library', 'floor', 1),('library', 'desk', 1),('library', 'table', 1),('library', 'maine', 1)]

Note that when the values match exactly, the order is arbitrary (except that items will always be grouped by key_1), if you would like some other behavior just edit your question with what you expect in these scenarios.

After obtaining this list, you could print it out by iterating over it like this:

for key_1, key_2, value in ordered:print key_1, key2, value         # add whatever formatting you want to here
https://en.xdnf.cn/q/118094.html

Related Q&A

How can I get python generated excel document to correctly calculate array formulas

I am generating some excel files with python using python 3.6 and openpyxl.At one point I have to calculate standard deviations of a subsection of data. In excel this is done with an array formula. Wri…

Unable to locate element in Python Selenium

Im trying to locate an element using python selenium, and have the following code:zframe = driver.find_element_by_xpath("/html/frameset/frameset/frame[5]") driver.switch_to.frame(zframe) find…

How to import a variable from a different class

I have an instance of a class that i set the value to self.world inside a class named zeus inside a module named Greek_gods. and i have another class names World inside a module name World.How can i te…

Scrapy: AttributeError: YourCrawler object has no attribute parse_following_urls

I am writing a scrapy spider. I have been reading this question: Scrapy: scraping a list of links, and I can make it recognise the urls in a listpage, but I cant make it go inside the urls and save the…

initializer is not a constant, error C2099, on compiling a module written in c for python

i tried to compile a python module called distance, whith c "python setup.py install --with-c" using msvc 2017 on windows 10, i got this error ,Cdistance / distance.c (647): error C2099: init…

How can make pandas columns compare check cell?

I have a two file. a.txt has the below data.Zone,Aliase1,Aliase2 VNX7600SPB3_8B3_H1,VNX7600SPB3,8B3_H1 VNX7600SPBA_8B4_H1,VNX7600SPA3,8B4_H1 CX480SPA1_11B3_H1,CX480SPA1,11B3_H1 CX480SPB1_11B4_H1,CX480S…

Flask argument of type _RequestGlobals is not iterable

When I tried to use Flask-WTForms, I followed these steps:from flask_wtf import Form from wtforms import StringField, PasswordField from wtforms.validators import DataRequired, Emailclass EmailPassword…

PumpStreamHandler can capture the process output in realtime

I try to capture a python process output via apache-commons-exec. But it looks like it wont print the output, the output is only displayed after I the python process is finished.Heres my java codeComma…

Freezing a CNN tensorflow model into a .pb file

Im currently experimenting with superresolution using CNNs. To serve my model Ill need to frezze it first, into a .pb file, right? Being a newbie I dont really know how to do that. My model basically …

flattening a list or a tuple in python. Not sure what the error is

def flatten(t):list = []for i in t:if(type(i) != list and type(i) != tuple):list.append(i)else:list.extend(flatten(i))return listHere is the function that Ive written to flatten a list or a tuple that …