Adding a Value to a Dictionary


numbers = ('1','2','3','4','5','6','7','8','9','0') letters = ('a','b','c','d','e','f') punct = ('.', '!', '?') charSetDict = {numbers:[], letters:[], punct:[]} cSet = raw_input("Insert characters: ") for c in cSet:     for x in charSetDict.keys():         if c in x:             charSetDict[x].append(c)             break; charSetDict["Special"] = ['%', '$', '#'] charSetDict["Special"] = '><'

Adding values to a dictionary is really just setting up a key in the dictionary to correspond to a specific value. When assigning a value to the dictionary, if the key you specify does not already exist in the dictionary, the key is added to the dictionary and the value is assigned to it. If the key already exists in the dictionary, the value object currently assigned to the key will be replaced by the new value object.

The object type of the value and key do not need to match, and at any time you can replace the value object with a new object of any type.

Note

Be aware that the keys in the dictionary are case sensitive. For example, Name and name would represent two completely distinct keys in the dictionary.


numbers = ('1','2','3','4','5','6','7','8','9','0') letters = ('a','b','c','d','e','f') punct = ('.', '!', '?') charSetDict = {numbers:[], letters:[], punct:[]} def display_cset (cset):     print     for x in cset.items():         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 cSet = raw_input("Insert characters: ") for c in cSet:     for x in charSetDict.keys():         if c in x:             charSetDict[x].append(c)             break; display_cset(charSetDict) #Add new key and value charSetDict["Special"] = ['%', '$', '#'] display_cset(charSetDict) #Change value for existing key charSetDict["Special"] = '><' display_cset(charSetDict)


add_dict.py

Insert characters: abc 123 . Numbers: ['1', '2', '3'] Puctuation: ['.'] Letters: ['a', 'b', 'c'] Numbers: ['1', '2', '3'] Puctuation: ['.'] Letters: ['a', 'b', 'c'] Unknown: ['%', '$', '#'] Numbers: ['1', '2', '3'] Puctuation: ['.'] Letters: ['a', 'b', 'c'] Unknown: ><


Output of add_dict.py



Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net