Darsh Darsh - 1 month ago 11
Python Question

Python: For defaultdict, print keys and values

This dictionary keeps on changing with keys and values. So, I want to access these keys and values and print it like expected answer. As I am new to Python, any help would be highly appreciated.

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']]}
}


Expected answer:

Name:key1 , Address:key10, Number:66619, Pin_code:event1

Name:key1 , Address:key10, Number:64800, Pin_code:event2

Name:key2 , Address:key11, Number:28250, Pin_code:event3

Name:key2 , Address:key11, Number:17960, Pin_code:event4

Name:key2 , Address:key11, Number:23484, Pin_code:event5

Name:key2 , Address:key11, Number:21945, Pin_code:event6

Name:key3 , Address:key12, Number:359319, Pin_code:event7

Name:key3 , Address:key12, Number:322334, Pin_code:event8

Name:key3 , Address:key12, Number:273316, Pin_code:event9

Name:key3 , Address:key13, Number:452945, Pin_code:event10

Name:key3 , Address:key13, Number:414268, Pin_code:event11

Answer

Dictionary are unordered in nature. You have to use 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.

If you just want to print this content without actually storing the sorted data, you may do it with simple sorted() function as:

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])   

which will print:

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