Skip to content
thesarfo

Reference

Dictionary Operators & Methods (Python)

How Python dictionaries are created, plus their core operators and methods.

views 0

You create a dictionary with curly braces, followed by a key and a value — just like a JSON object:

capitals = {'Ghana': 'Accra', 'Nigeria': 'Abuja', 'Cameroon': 'Yaounde'}

Dictionary Operators

  1. []capitals['Ghana'] — returns the value associated with the key Ghana, otherwise it’s an error.
  2. in'Ghana' in capitals — returns True if the key Ghana is in the dictionary, False otherwise.
  3. deldel capitals['Ghana'] — removes the entry Ghana from the dictionary.

Dictionary Methods

  1. keyscapitals.keys() — returns the keys of the dictionary in a dict_keys object.
  2. valuescapitals.values() — returns the values of the dictionary in a dict_values object.
  3. itemscapitals.items() — returns the key-value pairs in a dict_items object.
  4. getcapitals.get('Ghana') — returns the value associated with the key Ghana, None otherwise.
  5. getcapitals.get('Ghana', 'Not Found') — returns the value associated with the key Ghana, 'Not Found' otherwise.