How to make a dictionary of dictionaries with Python

Posted in howto , python

deck-of-cardsCreate 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

Related Posts

0 Comments

No comments yet. Be the first to leave a comment !
Leave a Comment

Name

Email

Website

*

Previous Post
«
Next Post
»
Powered by Wordpress   |   Lunated designed by ZenVerse

Valid XHTML 1.0 Transitional