迭代给定字典,同时保留其顺序

时间:2019-04-12 18:31:47

标签: python dictionary

我有一本嵌套的字典,其中有我想要的顺序。 但是,一旦我尝试在其中进行迭代,并尝试增加键,则对象的排序已经在第一个for循环中按字母顺序进行了排序,就放弃了增量。

given = {
    "testC": { "0": { "ccc": ["c100"] } },
    "testA": { "1": { "aaa": ["a100", "a200"] } }, 
    "testB": { "2": { "bbb": [] }}
}


index_order = 0

for k1, k2 in given.items(): # the ordering is change here, where testA will reordered
    for page_index_order in given[k1].keys():
        var = given[k1][page_index_order]

        if page_index_order != index_order:
            index_order += 1
        else:
            index_order = page_index_order

        given[k1][index_order] = var
        given[k1].pop(page_index_order)

pprint(given)

'''
{'testA': {1: {'aaa': ['a100', 'a200']}},
 'testB': {3: {'bbb': []}},
 'testC': {2: {'ccc': ['c100']}}}
'''

我期望我的结果是(相同的顺序,但是请注意索引值,我希望testC为1,但它却返回2):

{'testC': {1: {'ccc': ['c100']}},
 'testA': {2: {'aaa': ['a100', 'a200']}},
 'testB': {3: {'bbb': []}}}

我尝试在第一个OrderedDict(given)循环中使用for,但它返回了排序后的字典。

2 个答案:

答案 0 :(得分:0)

given = {
    "testC": { "0": { "ccc": ["c100"] } },
    "testA": { "1": { "aaa": ["a100", "a200"] } }, 
    "testB": { "2": { "bbb": [] }}
}
given_keys = ["testC", "testA", "testB"]  # decide order
sorted_given = OrderedDict([(k, given[k]) for k in given_keys])

答案 1 :(得分:0)

如果您使用Python 3.7+或collections.OrderedDict,则您的字典将被正确排序,但是如果您在Python 3.7+中使用常规字典,则问题将是pprint总是打印带有排序键的字典,别无选择。使用print来按其实际顺序输出字典键:

given = {
    "testC": { "0": { "ccc": ["c100"] } },
    "testA": { "1": { "aaa": ["a100", "a200"] } }, 
    "testB": { "2": { "bbb": [] }}
}

index_order = 0

for k1, k2 in given.items():
    for page_index_order in list(given[k1]):
        var = given[k1][page_index_order]

        if page_index_order != index_order:
            index_order += 1
        else:
            index_order = page_index_order

        given[k1][index_order] = var
        given[k1].pop(page_index_order)

print(given)

这将输出(在Python 3.7中):

{'testC': {1: {'ccc': ['c100']}}, 'testA': {2: {'aaa': ['a100', 'a200']}}, 'testB': {3: {'bbb': []}}}

或使用collections.OrderedDict

given = OrderedDict((
    ("testC", { "0": { "ccc": ["c100"] }}),
    ("testA", { "1": { "aaa": ["a100", "a200"] }} ),
    ("testB", { "2": { "bbb": [] }})
))

index_order = 0

for k1, k2 in given.items(): # the ordering is change here, where testA will reordered
    for page_index_order in list(given[k1]):
        var = given[k1][page_index_order]

        if page_index_order != index_order:
            index_order += 1
        else:
            index_order = page_index_order

        given[k1][index_order] = var
        given[k1].pop(page_index_order)

print(given)

这将输出:

OrderedDict([('testC', {1: {'ccc': ['c100']}}), ('testA', {2: {'aaa': ['a100', 'a200']}}), ('testB', {3: {'bbb': []}})])