Expected result:
main_dict = {
'a':
{ 0: 'Letter a',
1: 'Letter a',
2: 'Letter a',},
'b':
{ 0: 'Letter b',
1: 'Letter b',
2: 'Letter b',},
'c':
{ 0: 'Letter c',
1: 'Letter c',
2: 'Letter c',}
}
My program, version 1; the expected results is the output.
# my_program.py
def fill_dict(a_dict, a_key):
if not a_dict.has_key(a_key):
a_dict[a_key] = {}
for i in xrange(3):
a_dict[a_key][i] = 'Letter {}'.format(a_key)
def main():
main_dict = {}
a_list = ['a', 'b', 'c']
for item in a_list:
fill_dict(main_dict, item)
if __name__ == '__main__':
main()
Refactored program using defaultdicts
; result is main_dict = {}
.
# defaultdict_test.py
import collections
def fill_dict(a_dict, a_key):
a_dict = collections.defaultdict(dict)
for i in xrange(3):
a_dict[a_key][i] = 'Letter {}'.format(a_key)
def main():
main_dict = {}
a_list = ['a', 'b', 'c']
for item in a_list:
fill_dict(main_dict, item)
if __name__ == '__main__':
main()
Any pointers on what I'm doing wrong? Thanks.