Retrieving a Value from a Dictionary


validkeys = (1,2,3) keyGenDict={'keys':[1,2,3],1:'blue',2:'fast',             3:'test','key':2} print keyGenDict.keys() print keyGenDict.values() print keyGenDict.items() val = keyGenDict["key"] keyGenDict["key"] = 1 val = keyGenDict["key"]

A value can be retrieved from a dictionary using several different methods. The most common is to access the value directly by specifying the associated key in square brackets following the dictionary variable.

A list of values contained in a dictionary can be retrieved using the values() method. The values method returns a list containing all objects that are values in the dictionary.

Similarly, you can obtain just a list of keys using the keys() method. The keys method returns a list of objects that are currently being used as keys in the dictionary. The list of keys is useful in many ways, such as creating a tuple of the keys for faster lookups in the dictionary.

You can also get a list of key and value pairs by using the items() method. The items method returns a list that contains two-element tuples of each key and value pair in the dictionary.

validkeys = (1,2,3) keyGenDict={'keys':[1,2,3],1:'blue',2:'fast',             3:'test','key':2} def show_key (key):     if(key in validkeys):         keyVal = (keyGenDict["keys"])[key-1]         print "Key = " + keyGenDict[keyVal]     else:         print("Invalid key") #Retrieving dictionary key list print keyGenDict.keys() #Retrieving dictionary value list print keyGenDict.keys() #Retrieving dictionary value list print keyGenDict.items() #Retrieve value from key val = keyGenDict["key"] show_key(val) keyGenDict["key"] = 1 val = keyGenDict["key"] show_key(val)


ret_dict.py

['keys', 1, 2, 3, 'key'] [[1, 2, 3], 'blue', 'fast', 'test', 2] [('keys', [1, 2, 3]), (1, 'blue'), (2, 'fast'),  (3, 'test'), ('key', 2)] Key = fast Key = blue


Output of ret_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