Reputation: 4647
I have the following fairly complex data structure:
temp_dict = {
'a': {
'aardvark': (6,True),
'apple': (3,True)
},
'b':{
'banana': (2,False),
'bobble': (8,True)
}
}
print(temp_dict['a'])
It's a dictionary(temp_dict) that contains another dictionary layer (a,b), that contains another dictionary (aardvark, apple) that contain tuples.
But this outputs:
{'apple': (3, True), 'aardvark': (6, True)}
I don't mind the order of a,b; but I need the aardvark, apple
layer to be an orderedDict - they have to remember the order they were inserted in (which will never be sorted). So I've tried:
temp_dict = {
'a': OrderedDict{
'aardvark': (6,True),
'apple': (3,True)
},
'b':OrderedDict{
'banana': (2,False),
'bobble': (8,True)
}
}
But that just gives me invalid Syntax. How do I do this? None of the examples I've found has shown declaration of a OrderedDict within another data structure.
Thanks
Upvotes: 1
Views: 1567
Reputation: 11060
Do this:
temp_dict = {
'a': OrderedDict((
('aardvark', (6,True)),
('apple', (3,True))
)),
'b':OrderedDict((
('banana', (2,False)),
('bobble', (8,True))
))
}
(but also consider switching to using classes. I find that dictionaries with more than 1 layer of nesting are usually the wrong approach to a problem.)
Initializing an OrderedDict
with a dictionary guarantees insertion order being kept after the initialization.
>>> d = OrderedDict({1: 2, 3: 4})
>>> d[5] = 6
d
must now either be OrderedDict([(1, 2), (3, 4), (5, 6)])
or OrderedDict([(3, 4), (1, 2), (5, 6)])
.
On the other hand:
>>> d = OrderedDict([(1, 2), (3, 4)])
>>> d[5] = 6
d
can only now be OrderedDict([(1, 2), (3, 4), (5, 6)])
.
Upvotes: 2
Reputation: 15864
Try:
temp_dict = {
'a': OrderedDict([
('aardvark', (6,True)),
('apple', (3,True)),
]),
'b':OrderedDict([
('banana', (2,False)),
('bobble', (8,True)),
]),
}
Upvotes: 4