On 06/08/11 12:32, Norman Khine wrote:
hello,
i know that there are no indexes/positions in a python dictionary,
what will be the most appropriate way to do this:

                 addresses = {}
                 for result in results.get_documents():
                     addresses[result.name] = result.title
                 addresses['create-new-address'] = 'Create new address!'
                 return dumps(addresses)

so that when i return the 'dumps(addresses)', i would like the
'create-new-address' to be always at the last position.

Translating that into English, what I think you want is:

You want to print a dictionary (or return a string representation?) such that the last thing added to the dictionary is the last thing listed? Or, do you want the string representation to have all of the items in the order they were inserted?

Or do you want the string representation to always have the specific 'create_new_address' listed last regardless of where it was originally inserted?

And do you really want just a string representation in this order or do you really want the data stored and accessible in that order? (In which case don't use a dictionary!)

I guess the real question is why you need the dictionary in the first place? Dictionaries facilitate random access to your data based on key values. Is that a necessary feature of your application? If so use a dictionary but consider adding an index value to the data(*). You can then sort the dictionary based on that index. If you don;t need the random access aspect then store the data in a list of (key,value) tuples instead.

(*)One way to add an index is:

def insert_in_dict(d,key,val):
    d[key] = (len(d), val)

Obviously you need to drop the index when accessing the real values:

def get_real_val(d,key):
    return d[key][1]

And you could even clean all that up by creating a class derived from dict.

You can then sort the dictionary by providing a key function to extract the index to sorted()


HTH

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to