Python Dictionaries

  • a kind of container along with lists and tuples
  • a dictionary associates a 'key' with a 'value'
    • key is unique identifier
    • value is something we associate with that key
    • example: phonebook
      • keys: names
      • values: phone numbers
    • example: real word dictionary
      • keys: words
      • values: definition
    • example: US gov't
      • keys: social security number
      • values: info about an individual
  • in some languages called maps or associative arrays
  • dictionaries are mutable
    • changes made to dictionary in function persist after the function ends
  • does not store the data in order like lists and tuples with index values, stores in order added --- better to just think of it as unordered and use key/value lookups

creating

  • create with my_dict = dict() or my_dict = {}
    • start/end with {}
    • Key:Value pairs separated by colon
    • each pair separated by comma
    • example: ages = {'Chris': 32, 'Brahm': 23, 'Mehran': 50}

accessing elements

  • to look up/access a value use dict[key]
  • exception (KeyError) raised if you try to look up key that doesn't exist
    • use in or not in to see if a key is in a dictionary (called checking membership)
  • can also use dict.get(key) to access the value of a key
    • Returns None if the key doesn't exist
      • this is nice because you don't get a KeyError
    • if use dict.get(key, default) and the key doesn't exist, it will return the default
  • dict.keys() returns something similar to a range of the keys in dictionary
    • can loop over keys
      • for key in dict.keys():
              [whatever you want done to/with the keys/values]
    • use list(dict.keys()) to get a list of the keys
  • can loop over dictionary using a for-each loop with name of dictionary
    • for key in dict:          
        [whatever you want done to/with the keys/values]
  • dict.values() returns something similar to a range of the values in dictionary
    • can use that to loop over keys in dictionary
      • for values in dict.values():
              [whatever you want done to/with the keys/values]
    • use list(dict.values()) to get a list of the keys
  • you can use the key to look up the value
    • cannot directly check if a value is in a dictionary, so can't use the value to find the key

adding/removing elements

  • dict[key] = value assigns a value to a key
    • this will create the key if it doesn't already exist
    • if reassigned, it will overwrite existing value
    • example:
      phone = {}
      phone['Jenny'] = '867-5309'
    • also can use things like +=, -=, etc to update its value
  • del dict[key] will delete a key/value pair, no return value
  • dict.pop(key) removes the key/value pair, returns the value from that pair
  • dict.clear() empties the dictionary

about keys/values

  • keys must be immutable types
    • examples: int, float, string, tuple
    • if you want to change a key, you have to remove the key/value pair and then add a key/value pair with the new key
    • string keys are case-sensitive
  • values can be mutable or immutable
    • examples: int, float, string, tuple, list, dictionary
    • values can be changed in place (just reassign)

functions can apply

  • `len(dict)' returns number of key/value pairs

Copyright © 2022