# -*- coding: utf-8 -*- ''' @author: David ''' def main(): # Standard dict d = { 1 : 'London', 2 : 'New York' } print 'A standard dict:', d # Heterogenous items. Immutable keys, any object as values. d = { 1 : [1, 2, 3], 'a' : frozenset(['a', 1])} # Different methods of creating a dict var1 = 'key1' var2 = 'key2' d = { 'key1' : 3, 'key2' : 1.414 } # Method 1: d = dict(var1 = 3, var2 = 1.414) # Method 2, dict constructor-wrapping the first way of creating a dict: d = dict({'key1' : 3, 'key2' : 1.414}) # Method 3, zip merges two sequences into a single two-column sequence: # List 1 | List 2 | zip(List1, List2) # ----------+------------+------------------ # 1.0 | 3.0 | [1.0, 3.0] # 2.0 | 4.0 | [2.0, 4.0] d = dict(zip(['key1', 'key2'], [3, 1.414])) # Method 4, List of lists: d = dict([['key1', 3], ['key2', 1.414]]) # Empty dict d = {} d = dict() # Key lookup d = { 'key1' : 3, 'key2' : 1.414 } my_val = d['key1'] print "Dict value for 'key1':", my_val # Assigning new values to keys d['key1'] = 7 my_val = d['key1'] print "Dict value for 'key1':", my_val # Remove a mapping from the dict del d['key1'] print d # Length of a dict, i.e. number of mappings print 'Length of dict:', len(d) # Equality, comparisons etc. # Dictionaries compare equal if and only if their sorted (key, value) pairs # compare equal. # Other tests than equality, for example less than (<), greater than (>) # can't be trusted because there's no official definition of what the result # will be. This is also explained here: # http://docs.python.org/reference/expressions.html#not-in print "{1 : 'a'} == {1 : 'a'}?", {1 : 'a'} == {1 : 'a'} # True print "{1 : 'a', 2 : 'b'} == {2 : 'b', 1 : 'a'}?", {1 : 'a', 2 : 'b'} == {2 : 'b', 1 : 'a'} # True # Adding a mapping - 'key3' doesn't exist in dict before assignment print 'Before adding a key:', d d['key3'] = 11 print 'After adding a key:', d # Multiple assignment/unpacking works, but only gives you keys in unknown order k1, k2 = d print "Dict keys:", k1, k2 # Membership testing only applies to keys, not values print '11 in', d, '?:', 11 in d print 'key3 in', d, '?:', 'key3' in d # Dict comprehension is only available in v2.7+ # d = { key : val for key, val in enumerate('ABCDABCD') if val not in 'CB' } # print "Letters by index in 'ABCDABCD' (B and C excluded):", d # In v2.6 we need to resort to something like this instead of dict comprehensions: d = dict((key, val) for (key, val) in enumerate('ABCDABCD') if val not in 'CB') print "Letters by index in 'ABCDABCD' (B and C excluded):", d # Nested dictcomp not possible because of mutability # Get a (shallow) copy of a dict (1) d = { 1 : 'a', 2 : 'b' } my_dict2 = dict(d) my_dict2[3] = 'c' print 'Original and copy 1:', d, my_dict2 # Get a (shallow) copy of a dict (2) d = { 1 : 'a', 2 : 'b' } my_dict2 = d.copy() my_dict2[3] = 'c' print 'Original and copy 2:', d, my_dict2 # Minimum key of dict d = { 1 : 'a', 2 : 'b' } print 'Minimum of', d, 'is:', min(d) # Maximum key of dict d = { 1 : 'a', 2 : 'b' } print 'Maximum of', d, 'is:', max(d) # Index of a key doesn't exist because keys are unordered # Counting occurrences of keys isn't possible because keys are unique if __name__ == '__main__': main()
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question