473,748 Members | 4,935 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Order by value in dictionary

Hi..
I have a dictionary like these:
a={'a': '1000', 'b': '18000', 'c':'40', 'd': '600'} ...... 100.000
element
I want to sort this by value and i want to first 100 element..
Result must be:
[b, a, d, c .....] ( first 100 element)

I done this using FOR and ITERATOR but it tooks 1 second and this is
very big time to my project.
I want to learn the fastest method..

I'm sorry my bad english.
Please help me.
King regards..

Oct 17 '07 #1
4 1633
On Oct 17, 3:39 pm, Abandoned <best...@gmail. comwrote:
Hi..
I have a dictionary like these:
a={'a': '1000', 'b': '18000', 'c':'40', 'd': '600'} ...... 100.000
element
I want to sort this by value and i want to first 100 element..
Result must be:
[b, a, d, c .....] ( first 100 element)

I done this using FOR and ITERATOR but it tooks 1 second and this is
very big time to my project.
I want to learn the fastest method..

I'm sorry my bad english.
Please help me.
King regards..
I take it you did something like this
>>items = d.items()
items = [(v, k) for (k, v) in items]
items.sort( )
items.reverse () # so largest is first
items = [(k, v) for (v, k) in items]
?

Oct 17 '07 #2
Very very thanks everbody..

These are some method..
Now the fastest method is second..

==== 1 ===
def sortt(d):
items=d.items()
backitems=[ [v[1],v[0]] for v in items]
backitems.sort( )
#boyut=len(back items)
#backitems=back items[boyut-500:]
a=[ backitems[i][1] for i in range(0,len(bac kitems))]
a.reverse()
return a

==== 2 =====
import operator
def sortt(d):
backitems=d.ite ms()
boyut=len(backi tems)
backitems=backi tems[boyut-500:]
backitems=sorte d(backitems, key=operator.it emgetter(1))
a=[ backitems[i][0] for i in range(0,len(bac kitems))]
a.reverse()
return a

==== 3 =====
def sortt(d):
backitems=d.ite ms()
backitems.sort( lambda x,y:cmp(x[1],y[1]))
backitems=sorte d(backitems, key=operator.it emgetter(1))
a=[ backitems[i][0] for i in range(0,len(bac kitems))]
a.reverse()
return a

====== 4 =======
import heapq

def sortt(d):
backitems=d.ite ms()
backitems=heapq .nlargest(1000, backitems, operator.itemge tter(1))
a=[ backitems[i][0] for i in range(0,len(bac kitems))]
a.reverse()
return a

Oct 17 '07 #3
On Wed, 17 Oct 2007 08:09:50 -0700, Abandoned wrote:
Very very thanks everbody..

These are some method..
Now the fastest method is second..
Maybe because the second seems to be the only one that's not processing
the whole dictionary but just 500 items less!?

You are building way too much intermediate lists in your functions.
==== 1 ===
def sortt(d):
items=d.items()
Builds a list of all items.
backitems=[ [v[1],v[0]] for v in items]
Builds another list from all items.
backitems.sort( )
a=[ backitems[i][1] for i in range(0,len(bac kitems))]
And again a new list *plus* a list of len(backitems) integers that is
built just to iterate over it. Instead of iterating directly over
`backitems` without the index.
a.reverse()
return a
This whole function can be written as (untested):

def sortt(d):
sorted_items = sorted((item[1], item[0]) for item in d.iteritems(),
reverse=True)
return map(operator.it emgetter(1), sorted_items)
==== 2 =====
import operator
def sortt(d):
backitems=d.ite ms()
boyut=len(backi tems)
backitems=backi tems[boyut-500:]
backitems=sorte d(backitems, key=operator.it emgetter(1))
a=[ backitems[i][0] for i in range(0,len(bac kitems))]
a.reverse()
return a
Without throwing away 500 items:

def sortt(d):
sorted_items = sorted(d.iterit ems(),
key=operator.it emgetter(1),
reverse=True)
return map(operator.it emgetter(0), sorted_items)

Ciao,
Marc 'BlackJack' Rintsch
Oct 17 '07 #4
On 10/17/07, Abandoned <be*****@gmail. comwrote:
Very very thanks everbody..

These are some method..
Now the fastest method is second..

==== 1 ===
def sortt(d):
items=d.items()
backitems=[ [v[1],v[0]] for v in items]
backitems.sort( )
#boyut=len(back items)
#backitems=back items[boyut-500:]
a=[ backitems[i][1] for i in range(0,len(bac kitems))]
a.reverse()
return a

==== 2 =====
import operator
def sortt(d):
backitems=d.ite ms()
boyut=len(backi tems)
backitems=backi tems[boyut-500:]
backitems=sorte d(backitems, key=operator.it emgetter(1))
a=[ backitems[i][0] for i in range(0,len(bac kitems))]
a.reverse()
return a

==== 3 =====
def sortt(d):
backitems=d.ite ms()
backitems.sort( lambda x,y:cmp(x[1],y[1]))
backitems=sorte d(backitems, key=operator.it emgetter(1))
a=[ backitems[i][0] for i in range(0,len(bac kitems))]
a.reverse()
return a

====== 4 =======
import heapq

def sortt(d):
backitems=d.ite ms()
backitems=heapq .nlargest(1000, backitems, operator.itemge tter(1))
a=[ backitems[i][0] for i in range(0,len(bac kitems))]
a.reverse()
return a
Btw, there are specialized algorithms called "Selection Algorithms"
for finding k largest items in a collection.

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

Cheers,
--
--
Amit Khemka
Oct 18 '07 #5

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

Similar topics

2
7064
by: Brainwashed | last post by:
Is there any order in dictionaries that will never change ? I've noticed that assigning always the same elements to the dict puts them always in the same order. Like regexp which takes 3 values, 'year', 'month', 'day' - I always get this order: 'year': .., 'day':.., 'month':.. No idea why this order tho.. :) Is there any philosophy in this ? And if I add only one new value to this regexp, so that it takes 4 now the order changes...
0
1732
by: Christos TZOTZIOY Georgiou | last post by:
Hi all, this post contains at the end a handy module that I've used quite often when I wanted to analyse the occasional complex expression and how it was to be evaluated. The function analyse_expression is called with a single string argument containing an expression. Names are allowed (actually, preferred over numbers ;-), since the function eval's in a protected dictionary, where names are generated as needed.
2
3297
by: Tim Daneliuk | last post by:
I am aware that dictionary order is not guaranteed. But I ran into something puzzling today. I filled a dictionary dynamically as a program ran. Up to a certain point, the key order was the order in which things were added. However, at some point, the dictionary appeared to reorder its contents in some non-deterministic way - in fact, it looked like it was putting all the uppercase keys first, followed by lowercase keys. I'm just...
7
3665
by: svilen | last post by:
hello again. i'm now into using python instead of another language(s) for describing structures of data, including names, structure, type-checks, conversions, value-validations, metadata etc. And i have things to offer, and to request. And a lot of ideas, but who needs them.... here's an example (from type_struct.py):
39
2930
by: Nicolas Fleury | last post by:
In the following example: class MyMetaclass(type): pass class MyBaseType(object): __metaclass__ = MyMetaclass class MyType(MyBaseType): x = 4 y = 5 z = 6 Is there any way to modify MyMetaclass to keep the order of x,y,z somewhere?
5
2087
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
7
3099
by: Marcio Rosa da Silva | last post by:
Hi! In dictionaries, unlinke lists, it doesn't matter the order one inserts the contents, elements are stored using its own rules. Ex: >>> d = {3: 4, 1: 2} >>> d {1: 2, 3: 4}
2
31656
by: orekinbck | last post by:
Hi There I am probably missing something fundamental here, but I cannot see a method to search the values of a generic dictionary so that I can find the key ? Of course I could enumerate through the Values collection but that seems a little long winded. I ended up using a sorted list because it has the IndexOfValue method. However I don't need the sorting.
8
7924
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 =
8
13344
by: Brian L. Troutwine | last post by:
I've got a problem that I can't seem to get my head around and hoped somebody might help me out a bit: I've got a dictionary, A, that is arbitarily large and may contains ints, None and more dictionaries which themselves may contain ints, None and more dictionaries. Each of the sub-dictionaries is also arbitrarily large. When pretty printing A, in the context I'm using A for, it's rather helpful to remove all key:value pairs where value...
0
9541
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
9370
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9247
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8242
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
6796
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
4874
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3312
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
2782
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
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.