473,671 Members | 2,216 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

dictionary: sorting the values preserving the order

Hi,
For a particular problem of mine, I want to sort <key, value> pairs
by its value.

Eg:

Input:

A, 4
B, 5
C, 1
D, 2
E, 3

I would like the output to be:

C
D
E
A
B

i.e. I would like to get the keys in the sorted order of values.

I did google around a little bit. One solution to a similar problem
suggested is:

# Courtesy:
http://aspn.activestate.com/ASPN/Pyt...k/Recipe/52306
def sortedDictValue s3(adict):
keys = adict.keys()
keys.sort()
return map(adict.get, keys)

This gets a list sorted by the keys. How would I get a revised
dictionary
sorted by its values.

Jul 18 '05 #1
5 2079

hi,

assuming your key-value relationship is one-to-one then as a simple first
pass you can simply initialize d1={} and for i in d.keys(): d1[d[i]] = i
and pass d1 to your sortedDictValue 3 function, no?

thanks,
Vikram
On 31 Mar 2005, Rakesh wrote:
Hi,
For a particular problem of mine, I want to sort <key, value> pairs
by its value.

Eg:

Input:

A, 4
B, 5
C, 1
D, 2
E, 3

I would like the output to be:

C
D
E
A
B

i.e. I would like to get the keys in the sorted order of values.

I did google around a little bit. One solution to a similar problem
suggested is:

# Courtesy:
http://aspn.activestate.com/ASPN/Pyt...k/Recipe/52306
def sortedDictValue s3(adict):
keys = adict.keys()
keys.sort()
return map(adict.get, keys)

This gets a list sorted by the keys. How would I get a revised
dictionary
sorted by its values.


Jul 18 '05 #2
Rakesh wrote:
Hi,
For a particular problem of mine, I want to sort <key, value> pairs
by its value.

Eg:

Input:

A, 4
B, 5
C, 1
D, 2
E, 3

I would like the output to be:

C
D
E
A
B
the following code does that:
d1 = {'a':4,'b':5,'c ':1,'d':2,'e':3 }
i1 = [ (d1[i], i) for i in d1.keys() ]
i1.sort()
i1 [(1, 'c'), (2, 'd'), (3, 'e'), (4, 'a'), (5, 'b')] for each in i1:

.... print each[1]
c
d
e
a
b
thanks,
Satchit

i.e. I would like to get the keys in the sorted order of values.

I did google around a little bit. One solution to a similar problem
suggested is:

# Courtesy:
http://aspn.activestate.com/ASPN/Pyt...k/Recipe/52306
def sortedDictValue s3(adict):
keys = adict.keys()
keys.sort()
return map(adict.get, keys)

This gets a list sorted by the keys. How would I get a revised
dictionary
sorted by its values.

Jul 18 '05 #3
On 31 Mar 2005 22:40:53 -0800, "Rakesh" <ra***********@ yahoo.com>
wrote:
Hi,
For a particular problem of mine, I want to sort <key, value> pairs
by its value.

Eg:

Input:

A, 4
B, 5
C, 1
D, 2
E, 3

I would like the output to be:

C
D
E
A
B

i.e. I would like to get the keys in the sorted order of values.


Generally, dictionaries nearly always have two parts. The dictionary
itself, and a separate list of keys to access it with.

To access the dictionary in a particular order, you just need a sorted
key list.

Since what you want is to access by value, you need to create a second
dictionary with the values as the keys. That will only work if the
values never repeat. If they do, then you need to use a list and not a
dictionary.

This creates a second dictionary with a sorted value key list.

alpha_dict = {'A':4, 'B':5, 'C':1, 'D':2, 'E':3}

# Create a new dictionary with keys and values exchanged.
num_dict = {}
for k in alpha_dict.keys ():
num_dict[ alpha_dict[k] ] = k

# Get the num_dict keys and sort them.
num_keys = num_dict.keys()
num_keys.sort()
Ron

Jul 18 '05 #4
Another alternative:

d1 = {'a':4,'b':5,'c ':1,'d':2,'e':3 *}

il=[(v,k) for k,v in d1.items()]
il.sort()

Jul 18 '05 #5

"Rakesh" <ra***********@ yahoo.com> wrote in message
news:11******** **************@ l41g2000cwc.goo glegroups.com.. .
This gets a list sorted by the keys.
That is all you *can* get (with the list keys being the dict values).
How would I get a revised dictionary sorted by its values.


You can't. A dictionary is not sorted. The print order is arbitrary and
not controllable.

Terry J. Reedy

Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2894
by: Rory Campbell-Lange | last post by:
I have a dictionary of images. I wish to sort the dictionary 'v' by a dictionary value using python 2.3. The dictionary value is the date attribute as shown here: v This attribute is an extracted EXIF value from the following set: data element of v:
9
2578
by: jwedel_stolo | last post by:
Hi I'm creating a dataview "on the fly" in order to sort some data prior to writing out the information to a MS SQL table I have used two methods in order to determine the sort order of the DataView. (I'm writing in C# with the v1.1.4322 of the .NET Framework, in Window2K server"). First of all, here are the two methods I have used in order to apply the sorting property to the DataView 1. Simply defining the sort order and colum DataView...
12
2379
by: pmud | last post by:
Hi, I am using teh following code for sorting the data grid but it doesnt work. I have set the auto generate columns to false. & set the sort expression for each field as the anme of that field... This grid displayes results based on users search.. public static int numberDiv; private void Page_Load(object sender, System.EventArgs e) {
5
2303
by: JerryB | last post by:
Hi, I have a dictionary for counting ocurrences of strings in a document. The dictionary looks like this: 'hello':135 'goodbye':30 'lucy':4 'sky':55 'diamonds':239843 'yesterday':4
19
25452
by: Owen T. Soroke | last post by:
Using VB.NET I have a ListView with several columns. Two columns contain integer values, while the remaining contain string values. I am confused as to how I would provide functionality to sort columns based on the column header the user has clicked in both Ascending and Descending formats.
2
3742
by: Chris Kratz | last post by:
We are having a weird problem that we ran into recently. If I use the following statements to create a test table and then run the select statement at the end, we get a very strange sort order. It appears that to do the sorting, all the spaces are removed from the strings. It would appear that in the example below 'ab e' should be before 'abd'. create table testing_sort(col1 text); insert into testing_sort values('a'); insert into...
8
7916
by: spohle | last post by:
hi i have a normal dictionary with key and value pairs. now i wanna sort by the keys BUT in a specific order i determine in a list !? any ideas dic = {'key1':'value1', 'key2':'value2', 'key3':'value3'} list =
2
7221
by: jediknight | last post by:
Hi, I have a listview which has columns of text and columns of numerical data. I need to be able to sort these columns into ascending/desending order whenever the user clicks on the column header. The text columns are sorted correctly but the numerical columns seem not to get sorted properly. For example I get the following result when I try to sort a numerical
4
1850
by: rajtalent | last post by:
hi all, I want to sort the colum when clicks the columnheader using vb.net 2005 .But i receive the following error "Error 1 Overload resolution failed because no accessible 'New' accepts this number of arguments. " and my code is Private Sub ListView1_ColumnClick(ByVal sender As Object, ByVal e As System.Windows.Forms.ColumnClickEventArgs) Handles ListView1.ColumnClick If e.Column <> sortColumn Then sortColumn = e.Column...
0
8473
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8390
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8911
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
7428
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6222
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5692
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2808
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2048
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.