[Tutor] dictionary entries within dictionary
Jeff Shannon
jeff@ccvcorp.com
Mon Apr 7 22:05:03 2003
Paul Tremblay wrote:
>I can't figure out how to set up and access dictionaries within
>dictionaries.
>
>I set up my dictionary as follows:
>
>self.__styles_dict = {'para': {0:{}}, 'char':{0:{}}}
>
>Then try to add a value to this dictionary:
>
>self.__styles_dict[self.__type_of_style][self.__styles_num][att] = value
>
>I get an error message that key 15 cannot be found. In other words, I
>can't add a value to the inside entry of the dictionary.
>
>
If you're getting errors within dense lines like that, it often helps to
take things apart and look at them one step at a time. First, let's
reformat your dictionary definition so we can make a bit more sense of it:
self.__styles_dict = {
'para' : {
0 : {}
},
'char' : {
0 : {}
}
}
Now, look at the code in which you try to add something:
style_dict = self.__styles_dict[self.__type_of_style]
style = style_dict[self.__styles_num]
style[att] = value
Using these three lines in place of your one, we can see that
self.__type_of_style needs to be either 'para' or 'char', and that
currently, whichever of those it is, self.__styles_num must be 0. In
that case, you're adding 'att: value' to one of the most-deeply-nested
dicts, both of which start out empty.
I suspect that your problem is that self.__styles_num is actually 15,
and you have no such number defined within your style_dict.
If you want to be able to create new sub-dictionaries on the fly if they
don't already exist, then you can keep that line broken apart, and catch
the KeyErrors.
style_dict = self.__styles_dict[self.__type_of_style]
try:
style = style_dict[self.__styles_num]
except KeyError:
style = {}
style_dict[self.__styles_num] = style
style[att] = value
If you want to be able to create style types, as well, then you'll need
to catch the key error for the first dict access as well:
try:
style_dict = self.__styles_dict[self.__type_of_style]
except KeyError:
style_dict = { 0 : {} }
self.__styles_dict[self.__type_of_style] = style_dict
It might help to think of your nested dictionaries as a tree. Each item
that's another dictionary is a twig, and items within the
most-deeply-nested dictionaries (such as your att:value pair) are
leaves. (Try sketching out the structure, like you'd see for a family
tree.) Assignment, like your original code tries to do, can only create
new leaves, not new twigs. You have to build those twigs before you can
add leaves to them. (To stick with the family tree example, you need to
create children before those new children can have grandchildren...)
Hope this helps.
Jeff Shannon
Technician/Programmer
Credit International