Python:对于defaultdict,打印键和值

Python: For defaultdict, print keys and values

本问题已经有最佳答案,请猛点这里访问。

这本词典不断地用键和值来变化。所以,我想访问这些键和值,并像预期的答案一样打印出来。因为我对python还不熟悉,所以任何帮助都会非常感谢。

1
2
3
4
5
     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,地址:key10,号码:66619,密码:event1

姓名:key1,地址:key10,号码:64800,密码:event2

姓名:key2,地址:key11,号码:28250,密码:event3

姓名:key2,地址:key11,号码:17960,密码:event4

姓名:key2,地址:key11,号码:23484,密码:event5

姓名:key2,地址:key11,号码:21945,密码:event6

姓名:key3,地址:key12,号码:359319,密码:event7

姓名:key3,地址:key12,号码:322334,密码:event8

姓名:key3,地址:key12,号码:273316,密码:event9

姓名:key3,地址:key13,号码:452945,密码:event10

姓名:key3,地址:key13,号码:414268,密码:event11


这本词典本质上是无序的。如果你想在dict内维持订单,就必须使用collections.OrderedDict()。根据OrderedDict号文件:

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()功能进行打印,如下所示:

1
2
3
4
5
6
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])

将打印:

1
2
3
4
5
6
7
8
9
10
11
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