Is there a python data structure that is: keyed, ordered, and addressable via key and order?
I'm looking for a data structure that's a mix of OrderedDict but also addressable via an integer, depending on when the element was added.
i.e.
con开发者_运维技巧fig_key = OrderedDict([('Version_Number', 'a'),
('Hardware_Config', 'b'),
('Size_Of_Data', 'c'),
('Checksum', 'd')])
That will function like:
>> print config_key['Version_Number']
a
>> print config_key[0]
a
>> print config_key['Size_Of_Data']
c
>> print config_key[2]
c
>> for x in config_key:
>> print x
Version_Number
Hardware_Config
Size_Of_Data
Checksum
Any ideas?
If you're using Python 2.7+ then there's one built in.
http://docs.python.org/library/collections.html#collections.OrderedDict
edit: So it looks like the order of items is supported via pop operations, but you could do the equivalent of what you want via list(my_ordered_dict)[i]
where i
is an integer.
# Make your own like this...
class CustomOrderedDict(collections.OrderedDict):
def __getitem__(self,key):
try:
return self.values()[key]
except TypeError:
return super(CustomOrderedDict,self).__getitem__(key)
edits:
(Sorry about all these bugs, I just typed it up real quick to give you an idea of what to do.)
- fixed returning values instead of key
- fixed recursion flub
- switched list access to
[]
syntax, since, being a list, that makes more sense.
精彩评论