Is Python Smart Enough to do Sorting like this?

Stephen Horne steve at ninereeds.fsnet.co.uk
Sat Mar 13 05:00:39 EST 2004


I'm afraid I'm having some trouble figuring out what you mean...


On Sat, 13 Mar 2004 04:25:32 +0000, "shalendra chhabra"
<shalen_itbhu at hotmail.com> wrote:

>If one has a string and can this string be assigned to a dictionary and then 
>we can apply the sorting methods of dictionary on it.

You can't assign a string to a dictionary. You can assign a string to
a variable (which may or may not have previously held a dictionary) or
you can store a string in a dictionary.

If you intend to store the string in a dictionary, do you intend it to
be the key or the data? If the key, where does the data come from? If
the data, where does the key come from?

>For example: the information in my itemset can be treated as a string.
>
>itemset{}

Do you mean 'itemset = {}' ?

>itemset=str(key[i])+str(value[i]) #done over a loop and and then some how 
>can get everything concatenated

I'm pretty confused now, but let's make some guesses...


When you use the '=' operator, you are binding an object to a
variable. Any object previously bound to the variable is unbound
first. If no other references exist, it is discarded.

Thus, on running...

somevar = {}
somevar = "hello"

The second line does not add anything to the dictionary. The string
replaces the dictionary, and the dictionary is deleted.

If you want to add something to a dictionary, the usual method would
be...

somevar = {}              #  get an initial empty dictionary
somevar ['key'] = 'data'  #  add an item to the dictionary

You need both the key and the data. A dictionary maps keys to values,
much as a real dictionary maps words to their definitions.

Your 'key' and 'value' identifiers aren't defined anywhere. I'm
guessing that they're supposed to be accessing the keys and values
from the dictionary. To do this properly...

1.  You need to use the 'object.method' notation to access methods
    of objects. Python doesn't try to guess which object you intended.

2.  You can't access keys and values out of a dictionary using an
    integer loop index. You can, however, get a list of all the keys
    to iterate through. And when you have a key, you can access the
    data associated with it.

So lets try to put some of these elements together...

>>> #  Define a dictionary mapping some strings to integers
... d={"hello":1,"goodbye":2}
>>> d
{'hello': 1, 'goodbye': 2}
>>> #  List the keys
... d.keys()
['hello', 'goodbye']
>>> #  Show the data associated with one of the keys
... d ["hello"]
1
>>> #  Build a string describing the 'hello' item
... "hello : "+str(d["hello"])
'hello : 1'
>>> #  Create a list of strings describing the items in the dictionary
... [str(i)+" : "+str(d[i]) for i in d]
['hello : 1', 'goodbye : 2']
>>> #  Create a description of the whole dictionary
... ', '.join ([str(i)+" : "+str(d[i]) for i in d])
'hello : 1, goodbye : 2'



Does any of this help, or am I barking up the wrong tree?


>If I am not mistaken the itemset is now a string.
>How can I assign this itemset back to a dictionary? Is there any way?
>If yes! then we can apply the sort methods for increasing order and for 
>decreasing order you have given me the function already.

You can't sort a dictionary.

I suspect that my previous post left out too much explanation. Let's
examine that function again...

def pairs_by_decreasing_key (p_Dict) :
   """
   Takes a dictionary and derives a list of (key, value) tuples
   in decreasing order of key.
   """
   tmp = p_Dict.keys (); tmp.sort (); tmp.reverse ()

   return [(i, p_Dict [i]) for i in tmp]


This function contains a documentation string and four statements. The
four statements are...

1.  tmp = p_Dict.keys ()
2.  tmp.sort ()
3.  tmp.reverse ()
4.  return [(i, p_Dict [i]) for i in tmp]

The semicolons just allowed me to pack three statements on one line.
The following would mean the same thing...

The first statement gets a list of keys from the dictionary that is
passed in as a parameter. The result is not a dictionary - it is a
list.

For example...

>>> {"a":1,"b":2,"c":3}.keys()
['a', 'c', 'b']

The list of keys here is ['a', 'b', 'c'] because those are the keys
for the three items in the dictionary.

The second statement sorts the list. It does not affect the dictionary
in any way.

Similarly, the third statement reverses the order of the list and does
not affect the dictionary in any way.

The fourth statement constructs another list using a list
comprehension. It may be easier to understand without this...

def pairs_by_decreasing_key (p_Dict) :
   """
   Takes a dictionary and derives a list of (key, value) tuples
   in decreasing order of key.
   """
   tmp = p_Dict.keys (); tmp.sort (); tmp.reverse ()

   #  The following lines give the same effect as the
   #  list comprehension in the earlier version
   tmp2 = []

   for i in tmp :
     tmp2.append ( (i, p_Dict [i]) )

   return tmp2


I've tried to provide some hints, but I'm still pretty confused about
what you need. Does any of this help in any way?


-- 
Steve Horne

steve at ninereeds dot fsnet dot co dot uk



More information about the Python-list mailing list