Best way to emulate ordered dictionary (like in PHP)?

P

pyGuy

I am dealing with user profiles, which are simply a set of field-value
pairs. I've tried to many things to list, but for one, I tried creating
a wrapper class which inherits the dictionary and overrides the
iterator. Unfortunately I don't understand iterators enough to get this
working and before I waste any more time trying I figured I should
check wether there is a better way. I have run into a similar problem
once, and I resolved it by creating a wrapper class for the 'list'
class which overides the get_item method, checks for string parameter,
then accesses the appropriate item via a lookup 'list' contained within
the class which maps the string parameter to the index number (eh, it
just doesn't seem practical though). Now, I'e never used PHP, but
apparently, it's dictionaries retain the order in which the items are
entered and regurgitates them in that order when you iterate over them.
That is exactly what I want, but can't seem to get in Python. Any help?
Thanks in advance.
 
G

Georg Brandl

pyGuy said:
I am dealing with user profiles, which are simply a set of field-value
pairs. I've tried to many things to list, but for one, I tried creating
a wrapper class which inherits the dictionary and overrides the
iterator. Unfortunately I don't understand iterators enough to get this
working and before I waste any more time trying I figured I should
check wether there is a better way. I have run into a similar problem
once, and I resolved it by creating a wrapper class for the 'list'
class which overides the get_item method, checks for string parameter,
then accesses the appropriate item via a lookup 'list' contained within
the class which maps the string parameter to the index number (eh, it
just doesn't seem practical though). Now, I'e never used PHP, but
apparently, it's dictionaries retain the order in which the items are
entered and regurgitates them in that order when you iterate over them.
That is exactly what I want, but can't seem to get in Python. Any help?

If you search Google for OrderedDict, you get more than enough code snippets.
There's also one in the Python Cookbook, at
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438823

HTH,
Georg
 
P

pyGuy

Great, that recipe is exactly what I needed, and much cleaner than my
clumsy attempts. Thank you for your help.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top