Page Actions
Wiki Actions
User Actions
Submit This Story

Dictionary in Python

To create a dictionary that holds some many-to-many relationship. I used tuples as the key objects and list objects as the value objects in the dictionary.

The Code

#The tuples
numbers = ('1','2','3','4','5','6','7','8','9','0')
letters = ('a','b','c','d','e','f','g')
punct = ('.', '!', '?','...')
#The dictionary
charSetDict = {numbers:[], letters:[], punct:[]}
 
#Displays items in the dictionary
def display_charset (cset):
    print
    # The items method returns a list that contains two-element tuples of each key and value pair in the dictionary
    for x in cset.items():
        # Access a key
        if x[0] == numbers:
            print "Numbers:"
        elif x[0] == letters:
            print "Letters:"
        elif x[0] == punct:
            print "Puctuation:"
        else:
            print "Unknown:"
        print x[1]
 
 
#Add new values to keys
charSet = raw_input("Insert characters: ")
for c in charSet:
    for x in charSetDict.keys():
        if c in x:
            charSetDict[x].append(c)
            break;
 
#Display
display_charset(charSetDict)
 
 
#You can add new key n' value
charSetDict["Special"] = ['%', '$', '#']
display_charset(charSetDict)
 
#Or set value for existing key
charSetDict["Special"] = '><'
display_charset(charSetDict)
 
blog/2009/12/python_dict.txt · Last modified: 2009/12/01 00:00 (external edit)     Back to top
Recent changes RSS feed Creative Commons License Powered by PHP Driven by DokuWiki