Python:对于defaultdict,打印键和值

时间:2016-11-09 18:09:11

标签: python defaultdict

此词典随着键和值不断变化。所以,我想访问这些键和值,并像预期的答案一样打印它。由于我是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,地址:key10,编号:66619,Pin_code:event1

名称:key1,地址:key10,数字:64800,Pin_code:event2

名称:key2,地址:key11,Number:28250,Pin_code:event3

名称:key2,地址:key11,Number:17960,Pin_code:event4

名称:key2,地址:key11,编号:23484,Pin_code:event5

名称:key2,地址:key11,编号:21945,Pin_code:event6

名称:key3,地址:key12,编号:359319,Pin_code:event7

名称:key3,地址:key12,编号:322334,Pin_code:event8

名称:key3,地址:key12,编号:273316,Pin_code:event9

名称:key3,地址:key13,编号:452945,Pin_code:event10

名称:key3,地址:key13,编号:414268,Pin_code:event11

1 个答案:

答案 0 :(得分:1)

字典本质上是无序的。如果您想在dict内维护订单,则必须使用collections.OrderedDict()。根据{{​​3}}:

  

返回一个dict子类的实例,支持通常的dict   方法。 OrderedDict是一个记住键的顺序的dict   最先插入。如果新条目覆盖现有条目,则   原始插入位置保持不变。删除条目和   重新插入它将把它移到最后。

如果您只想打印此内容而不实际存储已排序的数据,则可以使用简单的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