How to make a dictionary of dictionaries with Python

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.

|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#!/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] |