[Tutor] adding dictionary value at position [-1]

Peter Otten __peter__ at web.de
Sat Aug 6 18:18:07 CEST 2011


Alan Gauld wrote:

> 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.

In Python 2.7 there is already such a class: collections.OrderedDict:

>>> from collections import OrderedDict
>>> up = OrderedDict.fromkeys("abc")
>>> down = OrderedDict.fromkeys("cba")
>>> up
OrderedDict([('a', None), ('b', None), ('c', None)])
>>> down
OrderedDict([('c', None), ('b', None), ('a', None)])




More information about the Tutor mailing list