简体   繁体   English

在字典声明中使用OrderedDict

[英]Using an OrderedDict within a dictionary declaration

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. 这是一本字典(temp_dict),其中包含另一个字典层(a,b),其中另一个字典层(aardvark,apple)包含元组。

But this outputs: {'apple': (3, True), 'aardvark': (6, True)} 但这会输出: {'apple': (3, True), 'aardvark': (6, True)}

I don't mind the order of a,b ; 不在乎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). 但是我需要将aardvark, apple层设置为orderedDict-他们必须记住插入的顺序(永远不会排序)。 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. 我发现的所有示例都未在另一个数据结构中显示OrderedDict的声明。

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. 使用字典初始化OrderedDict可以确保在初始化保持插入顺序。

>>> 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)]) . d现在必须是OrderedDict([(1, 2), (3, 4), (5, 6)])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)]) . d现在只能是OrderedDict([(1, 2), (3, 4), (5, 6)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM