Package basics :: Module dictionaries
[hide private]
[frames] | no frames]

Source Code for Module basics.dictionaries

 1  """ 
 2  Dictionaries store mappings between many kinds of data types. 
 3   
 4  First and most commonly, strings can be the 'keys' of a dictionary: 
 5   
 6     >>> X = {'x':42, 'y': 3.14, 'z':7} 
 7     >>> Y = {1:2, 3:4}   
 8     >>> Z = {}  
 9   
10  Make some assignments into a dict 
11     >>> L = dict(x=42,y=3.14,z=7)   
12   
13  The following is the way to do the same with integer keys. 
14   
15    >>> M = dict([[1, 2],[3, 4]]) 
16   
17  Retrieving values:   
18   
19    >>> X['x'] 
20    42 
21    >>> X['y'] 
22    3.1400000000000001 
23    >>> M[1] 
24    2 
25   
26  The following raises a KeyError: 
27    >>> X['w'] 
28    ... 
29    KeyError: 'w' 
30   
31  Dictionaries and lists can be interleaved. Lists can contain dictionaries 
32  and vice versa: 
33   
34    >>> Double = [{'x':42,'y': 3.14, 'z':7},{1:2,3:4},{'w':14}] 
35   
36  Any expression which has a Dictionary as its value may be followed 
37  by '[C{key}]'. The entire expresion then has the value of that key 
38  as its value. 
39   
40    >>> Double[0] 
41    {'y': 3.1400000000000001, 'x': 42, 'z': 7} 
42    >>> Double[0]['x'] 
43    42 
44   
45  """ 
46   
47 -def demo_dicts():
48 global X, Y, Z, L, M, Double 49 50 X = {'x':42, 'y': 3.14, 'z':7} # Dictionary with 3 items 51 Y = {1:2, 3:4} # Dictionary with two items, integer keys 52 Z = {} # empty dictionary 53 54 L = dict(x=42,y=3.14,z=7) # make a string a dict 55 # M = dict(1=2,3=4) # SyntaxError: keyword can't be an expression 56 M = dict([[1, 2],[3, 4]]) 57 58 X['x'] # 42 59 X['y'] # 3.14 60 M[1] # 2 61 62 ### mixed data type: a list of dictionaries. 63 Double = [{'x':42,'y': 3.14, 'z':7},{1:2,3:4},{'w':14}]
64 65 if __name__ == '__main__': 66 demo_dicts() 67