Sorting Driving Crazy: URGENT: PLEASE HELP
xtian
xtian at toysinabag.com
Sat Mar 13 06:26:00 EST 2004
dont bother <dontbotherworld at yahoo.com> wrote in message news:<mailman.346.1079159911.19534.python-list at python.org>...
> This is really driving me crazy.
>
> I have a dictionary feature_vectors{}. I try to sort
> its keys using
>
> #apply sorting on feature_vectors
> sorted_feature_vector=feature_vectors.keys()
> sorted_feature_vector.sort()
>
> #feature_vector.keys()=sorted_feature_vector
>
> new_feature_element={}
> new_feature_vector={}
>
> for x in sorted_feature_vector:
> print "SORTING\n"
> print x, '\t',feature_vectors[x]
> count=0
> if(count==0):
> new_feature_element=str(1)+"
> "+str(x)+":"+str(feature_vectors[x])+" "
> else:
>
> new_feature_element=str(x)+":"+str(feature_vectors[x])+"
> "
> count=count+1
>
> new_feature_vector=str(new_feature_vector)+str(new_feature_element)
> new_feature_vector=new_feature_vector+"\n"
>
> print "New Dictionary"
>
>
> When I print x and feature_vectors[x] I get some of
> the entries which are not in the increasing order.
>
> 22836 7.46464646465
> SORTING
>
> 22840 2.19977553311
> SORTING
>
> 22841 2.69809203143
> SORTING
>
> 22842 0.617283950617
> SORTING
>
> 22844 4.61279461279
> SORTING
>
> 22846 93.1537598204
> SORTING
>
> 2357 0.00224466891134
> SORTING
>
> 3105 0.00224466891134
> SORTING
>
> 3117 0.00224466891134
> SORTING
>
> 3675 0.003367003367
> SORTING
>
> 4280 0.00224466891134
> SORTING
>
The keys of your feature_vectors dictionary are strings - they have
been sorted lexicographically. The string "22846" is less than the
string "2357".
To check this, you can put:
print "Type of x is", type(x)
into your loop. It will be <type 'str'>, while you want <type 'int'>.
To convert feature_vectors into a dictionary with integer keys, use
this:
new_feature_vectors = {}
for key, value in feature_vectors:
new_feature_vectors[int(key)] = value
Then new_feature_vectors.keys() should be able to be sorted to have
the order you want.
On a side note, you seem to be having a lot of difficulty getting a
program to do what you want - have you worked through the tutorial
<http://www.python.org/doc/current/tut/tut.html>? The interactive
prompt can be very useful to check that snippets of code do what you
think they do.
Cheers,
xtian
More information about the Python-list
mailing list