Create a simple class of dictionaries so you can make a dictionary of dictionaries. No need for generators, iterators or funky lambdas at all here. Let’s take a deck of cards as an example. Four suits with thirteen cards per suit.
#!/usr/bin/env python
class DiDictionary(dict):
'''Dictionary of dictionaries'''
def __init__(self, in_dict):
self.d = in_dict
def __getitem__(self, key):
if not self.has_key(key):
self[key] = self.d()
return dict.__getitem__(self, key)
if __name__ == "__main__":
deck = DiDictionary(dict)
suits = [ 'Hearts','Spades','Clubs','Diamonds' ]
cards = [ 'Two','Three','Four','Five','Six','Seven','Eight',
'Nine','Ten','Jack','Queen','King','Ace' ]
for suit in suits:
for card in cards:
deck[suit][card] = '%s of %s' % (card, suit)
print deck[suit][card]
Posted by admica @ 18 October 2011