Dict
  • maps hashable values to arbitrary objects
  • mutable
  • More than one entry per key not allowed
  • Keys must be immutable, like strings, numbers, or tuples
  • Initialize a dict
    1. # Create a dict
    2. dict = {}
    3.  
    4. # Create a dict with initial values
    5. dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
    Update
    1. # Change the value of a key word
    2. dict['Name'] = 'Lin'
    3.  
    4. # Add a new key and value
    5. dict['Major'] = 'CS'
    Delete
    1. # Delete an element of the dict
    2. del dict['Name']
    3.  
    4. # Remove all elements of the dict
    5. dict.clear()
    6.  
    7. # Remove the whole dict
    8. del dict
    Build-in functions
    1. # cmp, compare two dicts
    2. dict1 = {'Name':'Lin', 'Age':37}
    3. dict2 = {'Name':'Lin', 'Age':37}
    4. print cmp(dict1, dict2)
    5.  
    6. #len, get the number of items in dict
    7. print len(dict1)
    8.  
    9. #str, convert a dict to a string
    10. print str(dict1)
    11.  
    12. #type, check type
    13. print type(dict1)
    14.  
    15. #id, get the memory id of the dict
    16. print id(dict1)
    Methods
    1. #!/usr/bin/python
    2.  
    3. d = {}; #create a dict
    4.  
    5. d['Name'] = 'Lin';
    6. d['Age'] = 38;
    7.  
    8. #has_key()
    9. if d.has_key('Name'):
    10. print 'Has key \'Name\'';
    11. if 'Name' in d:
    12. print 'Has key \'Name\'';
    13.  
    14. #get, returns a value for the given key; if key is not available then returns default value
    15. print d.get('Name');
    16. print d.get('Temp', 'Unknown');
    17. #print d['Temp']; # throw KeyError
    18.  
    19. #items, return a list of tuples of (key, value) pairs
    20. items = d.items();
    21. print items
    22.  
    23. #keys, return a list of keys
    24. keys = d.keys();
    25. print keys;
    26.  
    27. #values, return a list of values
    28. values = d.values();
    29. print values
    30.  
    31. #setdefault, get the value of key; if key is not available then return default value
    32. print d.setdefault('Age', None); #38
    33. print d.setdefault('Sex', None); #None
    34.  
    35. #update, add a dict to another dict
    36. d2 = {'Sex': 'M', 'State': 'VA'};
    37. d.update(d2); #{'Name':'Lin', 'Age':38, 'Sex':'M', 'State':'VA'}
    38. print d
    39.  
    40. #remove and retun an arbitrary key-value pair
    41. print d.popitem();
    1. #!/usr/bin/python
    2.  
    3. d = {'Name': 'Lin', 'Age': 38, 'Sex': 'M', 'State': 'VA'};
    4.  
    5. #iterkeys
    6. i = d.iterkeys();
    7.  
    8. while 1:
    9. try:
    10. e = i.next();
    11. except StopIteration:
    12. break;
    13. else:
    14. print e,
    15. print
    16.  
    17. #itervalues
    18. iv = d.itervalues();
    19. for v in iv:
    20. print v,
    21. print
    22.  
    23. #iteritems
    24. it = d.iteritems();
    25. for t in it:
    26. print t;
    Resources
  • Python How to Program
  • STL