[Tutor] Having list in dict type
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Tue, 4 Dec 2001 13:42:36 -0800 (PST)
On Tue, 4 Dec 2001, Mariappan, MaharajanX wrote:
> Hi Folks!
>
> Is it posible for dictionary type's value part to be a list like below,
>
> { "key1", ["name", "value"]
> "key2", ["name", "value"]
Sure: if we try this in the interpreter:
###
>>> mydict = {}
>>> mydict = { "key" : ['name', 'value'],
... 'key2' : ['name', 'value'] }
>>> mydict
{'key': ['name', 'value'], 'key2': ['name', 'value']}
###
we can see that this works well. Python's data structures can be nested
arbitrarily deep, so we can even do something very silly like this with
lists:
###
>>> def cover(thing, depth):
... while depth > 0:
... thing = [thing]
... depth = depth - 1
... return thing
...
>>> buried_treasure = cover('gold coin', 10)
>>> buried_treasure
[[[[[[[[[['gold coin']]]]]]]]]]
###
and this flexibility extends to dictionaries too:
###
>>> treasures_of_the_deep = { 'gold coin' : cover('gold coin', 10),
... 'mythril' : cover('mythril', 7),
... 'masamune' : cover('masamune', 14) }
>>> treasures_of_the_deep
{ 'mythril': [[[[[[['mythril']]]]]]],
'masamune': [[[[[[[[[[[[[['masamune']]]]]]]]]]]]]],
'gold coin': [[[[[[[[[['gold coin']]]]]]]]]] }
###
> 1) how can I gennerate this data dynamically[ Asuume that I have all
> the sting values]
This depends on how your data is organized. If it looks like you're
traversing, one by one, through your string values, then using a 'for'
loop might work well. Can you give us some sample data, and your
expectation of what the dictionary should look like?
We can always add new entries into a dictionary like this:
###
>>> treasures_of_the_deep['pearl'] = cover('pearl', 99)
###
so if we combine something like this with a loop, we should be able to
insert elements dynamically into a dictionary.
> 2) Hiw can I traverse and print all the strings from this data.
We can 'walk' down dictionaries with the items() method. For example,
with that dictionary above:
###
>>> mydict = { "key" : ['name', 'value'],
... 'key2' : ['name', 'value'] }
>>> for key, value in mydict.items():
... print "The key %s unlocks the value %s" % (key, value)
...
The key key unlocks the value ['name', 'value']
The key key2 unlocks the value ['name', 'value']
###
You might want to look at the dictionary documentation here:
http://www.python.org/doc/lib/typesmapping.html
which covers what we can do with dictionaries in excruciating detail.
It's not thrilling reading, but it might come in handy.
Hope this helps!