Вопрос

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

Это было полезно?

Решение

Try:

temp_dict = {
    'a': OrderedDict([
        ('aardvark', (6,True)),
        ('apple', (3,True)),
    ]),
    'b':OrderedDict([
        ('banana', (2,False)),
        ('bobble', (8,True)),
    ]),
}

Другие советы

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top