Multidimensional Dictionaries: Possible?
Sean Blakey
seanb at home.com
Mon Jan 24 19:36:59 EST 2000
On Tue, 25 Jan 2000, Jerry Gardner wrote:
>
> Are multidimensional dictionaries possible in Python? I'm sure they're
> possible, but I can't figure out the syntax.
>
> Here's how I do it in Perl:
>
>
> %dict = (); # create empty dictionary
>
>
> $dict{$key1}{$key2} = $string; # make an entry
> $newstring = ${dict{$key1}{$key2}}; # access an entry
>
>
>
You might want to try something like this:
>>my_dict = {} # Create the dictionary
>>>try: # Make an entry
... my_dict[key1][key2] = my_string
...except KeyError:
... my_dict[key1] = {} # Create the dictionary in key1
... my_dict[key1][key2] = my_string
...
>>>string_reference = my_dict[key1][key2] # Access the string
Alternately, if this usage of try/except makes you uncomfortable:
>>>my_dict = {} # Create the dictionary
>>>if not my_dict.has_key(key1):
... my_dict[key1] = {}
...my_dict[key1][key2] = my_string
>>>string_reference = my_dict[key1][key2]
--
Sean Blakey
(206)297-7123
quine = ['print "quine =",quine,"; exec(quine[0])"']; exec(quine[0])
More information about the Python-list
mailing list