473,387 Members | 1,899 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Dictionary sorting problem

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

I want to print the dictionary so I see most common words first:

'diamonds':239843
'hello':135
'sky':55
'goodbye':30
'lucy':4
'yesterday':4

How do I do this? Notice I can't 'swap' the dictionary (making keys
values and values keys) and sort because I have values like lucy &
yesterday which have the same number of occurrences.

Thanks.

Sep 16 '05 #1
5 2295
JerryB wrote:
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

I want to print the dictionary so I see most common words first:

'diamonds':239843
'hello':135
'sky':55
'goodbye':30
'lucy':4
'yesterday':4

How do I do this? Notice I can't 'swap' the dictionary (making keys
values and values keys) and sort because I have values like lucy &
yesterday which have the same number of occurrences.

Thanks.


Don't try to 'swap' the dict, just sort a list based on the items in
the dict. Try this:

original= {
'hello':135,
'goodbye':30,
'lucy':4,
'sky':55,
'diamonds':239843,
'yesterday':4 }

items = sorted( (v,k) for (k,v) in original.iteritems() )
items.reverse() # depending on what order you want
print items
The result is:
[(239843, 'diamonds'), (135, 'hello'), (55, 'sky'), (30, 'goodbye'), (4, 'yesterday'),
(4, 'lucy')]
--Irmen
Sep 16 '05 #2
You can't sort dictionaries (as implemented by hash tables), they are
unordered data types, so by definition there's no way to force an order
on them.

http://en.wikipedia.org/wiki/Hash_tables

Sep 16 '05 #3
On Fri, 16 Sep 2005 21:42:40 +0200, Irmen de Jong <ir**********@xs4all.nl> wrote:
JerryB wrote:
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

I want to print the dictionary so I see most common words first:

'diamonds':239843
'hello':135
'sky':55
'goodbye':30
'lucy':4
'yesterday':4

How do I do this? Notice I can't 'swap' the dictionary (making keys
values and values keys) and sort because I have values like lucy &
yesterday which have the same number of occurrences.

Thanks.


Don't try to 'swap' the dict, just sort a list based on the items in
the dict. Try this:

original= {
'hello':135,
'goodbye':30,
'lucy':4,
'sky':55,
'diamonds':239843,
'yesterday':4 }

items = sorted( (v,k) for (k,v) in original.iteritems() )
items.reverse() # depending on what order you want
print items
The result is:
[(239843, 'diamonds'), (135, 'hello'), (55, 'sky'), (30, 'goodbye'), (4, 'yesterday'),
(4, 'lucy')]

or tell sorted what to do ;-)
original= { ... 'hello':135,
... 'goodbye':30,
... 'lucy':4,
... 'sky':55,
... 'diamonds':239843,
... 'yesterday':4 } list(sorted(original.iteritems(), None, lambda t:t[1], True))

[('diamonds', 239843), ('hello', 135), ('sky', 55), ('goodbye', 30), ('yesterday', 4), ('lucy',4)]

Regards,
Bengt Richter
Sep 17 '05 #4
Bengt Richter wrote:
or tell sorted what to do ;-)
original= { ... 'hello':135,
... 'goodbye':30,
... 'lucy':4,
... 'sky':55,
... 'diamonds':239843,
... 'yesterday':4 } list(sorted(original.iteritems(), None, lambda t:t[1], True)) [('diamonds', 239843), ('hello', 135), ('sky', 55), ('goodbye', 30),
('yesterday', 4), ('lucy',4)]


or a slight variation on this theme which just gives you the keys in value
order rather than the tuples:
for k in sorted(original, key=original.get, reverse=True):

print k, original[k]
diamonds 239843
hello 135
sky 55
goodbye 30
yesterday 4
lucy 4
Sep 17 '05 #5
On 17 Sep 2005 11:01:41 GMT, Duncan Booth <du**********@invalid.invalid> wrote:
Bengt Richter wrote:
or tell sorted what to do ;-)
>>> original= { ... 'hello':135,
... 'goodbye':30,
... 'lucy':4,
... 'sky':55,
... 'diamonds':239843,
... 'yesterday':4 }
>>> list(sorted(original.iteritems(), None, lambda t:t[1], True))

[('diamonds', 239843), ('hello', 135), ('sky', 55), ('goodbye', 30),
('yesterday', 4), ('lucy',4)]


or a slight variation on this theme which just gives you the keys in value
order rather than the tuples:
for k in sorted(original, key=original.get, reverse=True):

print k, original[k]

Nice. I like the keyword usage too. Much clearer than my hastypaste ;-)

diamonds 239843
hello 135
sky 55
goodbye 30
yesterday 4
lucy 4


Regards,
Bengt Richter
Sep 17 '05 #6

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

Similar topics

2
by: Jocknerd | last post by:
I have a list called teamlist which contain dictionaries of teams. These are the fields in my team dictionary: name, won, lost, tied, pf, pa To print standings I do the following: def...
4
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...
2
by: Anthony Liu | last post by:
I have a dictionary which contains some words and their frequency in a short novel. It looks like this: mydict = {'the':358, 'they':29, 'went':7, 'said':65} Is there an easy to sort this...
5
by: Rakesh | last post by:
Hi, For a particular problem of mine, I want to sort <key, value> pairs by its value. Eg: Input: A, 4 B, 5
9
by: Odd-R. | last post by:
I have a dictionary, and I want to convert it to a tuple, that is, I want each key - value pair in the dictionary to be a tuple in a tuple. If this is the dictionary {1:'one',2:'two',3:'three'},...
10
by: Petr Jakeš | last post by:
I have a standard 12-key mobile phone keypad connected to my Linux machine as a I2C peripheral. I would like to write a code which allows the text entry to the computer using this keypad (something...
1
by: Sam Loxton | last post by:
Hi, I am fairly new to the python language and am trying to sort a nested Dictionary of a Dictionary which I wish to sort by value. The dictionary does not have to be restructured as I only need...
5
by: Martin Pöpping | last post by:
Hello, I´ve a simple question about existing data structures/ collections. Is there a way to sort a dictionary (or any comparable collection/ data structure) by values instead of by keys? ...
5
by: =?Utf-8?B?THVpZ2k=?= | last post by:
Hi all, having a List<stringand Dictionary<int, stringhow can I check that every string in the list is also in the Dictionary (and viceversa)? (and raise an exception when not). Thanks in...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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,...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.