Python:对于defaultdict,打印键和值

Python: For defaultdict, print keys and values

这本词典会随着键和值的变化而不断变化。所以,我想访问这些键和值并像预期的答案一样打印出来。由于我是 Python 的新手,我们将不胜感激任何帮助。

     dictionary=
       {'key1': {'key10': [[66619, 'event1'], [64800, 'event2']]},
        'key2': {'key11': [[28250, 'event3'], [17960, 'event4'], [23484, 'event5'], [21945, 'event6']]},
        'key3': {'key12': [[359319, 'event7'], [322334, 'event8'], [273316, 'event9']], 'key13': [[452945, 'event10'], [414268, 'event11']]}
       } 

预期答案:

名称:key1 , Address:key10, Number:66619, Pin_code:event1

名称:key1 , Address:key10, Number:64800, Pin_code:event2

名称:key2 , Address:key11, Number:28250, Pin_code:event3

名称:key2 , Address:key11, Number:17960, Pin_code:event4

名称:key2 , Address:key11, Number:23484, Pin_code:event5

名称:key2 , Address:key11, Number:21945, Pin_code:event6

名称:key3 , Address:key12, Number:359319, Pin_code:event7

名称:key3 , Address:key12, Number:322334, Pin_code:event8

名称:key3 , Address:key12, Number:273316, Pin_code:event9

名称:key3 , Address:key13, Number:452945, Pin_code:event10

名称:key3 , Address:key13, Number:414268, Pin_code:event11

字典本质上是无序的。你必须使用 collections.OrderedDict() if you want to maintain the order within dict. As per the OrderedDict document:

Return an instance of a dict subclass, supporting the usual dict methods. An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.

如果您只想打印此内容而不实际存储排序后的数据,您可以使用简单的 sorted() 函数来实现:

from operator import itemgetter

for k, v in sorted(dictionary.items(), key=itemgetter(0)):
    for k1, v1 in sorted(v.items(), key=itemgetter(0)):
        for content in v1:
            print 'Name: {}, Address: {}, Number: {}, Pin: {}'.format(k, k1, content[0], content[1])   

这将打印:

Name: key1, Address: key10, Number: 66619, Pin: event1
Name: key1, Address: key10, Number: 64800, Pin: event2
Name: key2, Address: key11, Number: 28250, Pin: event3
Name: key2, Address: key11, Number: 17960, Pin: event4
Name: key2, Address: key11, Number: 23484, Pin: event5
Name: key2, Address: key11, Number: 21945, Pin: event6
Name: key3, Address: key12, Number: 359319, Pin: event7
Name: key3, Address: key12, Number: 322334, Pin: event8
Name: key3, Address: key12, Number: 273316, Pin: event9
Name: key3, Address: key13, Number: 452945, Pin: event10
Name: key3, Address: key13, Number: 414268, Pin: event11