Python Dictionaries

Python Dictionary [] index operator

Using the index [] operator, the value in a dictionary can be retrieved or set. If the key doesn't exist, Python will throw a KeyError exception.

Python Dictionary copy() Method

Copies all the items in the dictionary to another dictionary which is then returned. Changes to the old dictionary do not the copied dictionary, and changes in the copied dictionary do not affect the old dictionary.

Python Dictionary fromkeys() Method

Returns a dictionary from a list of keys and sets them all to the specified value. If the value is omitted, the value all keys are set to is None.

Python Dictionary get() Method

Returns the value of the specified key.

Python Dictionary items() Method

Returns a list containing the tuple for each key-value pair. This is what Python calls a "view object" which means that the object can only be viewed - it cannot be changed, nor can the tuple items be accessed.

Python Dictionary keys() Method

Returns a list of the dictionary's keys. The returned object is a "view object" - it cannot be changed.

Python Dictionary pop() Method

Removes the element with the specified key, and returns that value, or returns a default value if they key isn't found in the dictionary.

Python Dictionary clear() Method

Removes all elements from the dictionary.

Python Dictionary popitem() Method

Removes the last key-value pair that was inserted and returns that key-value pair as a tuple.

Python Dictionary setdefault() Method

Returns the value of the item with the specified key. If the key doesn't exist, the key is inserted into the dictionary with the supplied value, and that value is returned. If the key doesn't exist and no default value is supplied, nothing is returned.

Python Dictionary update() Method

Updates the dictionary with the specified key-value pairs. If the key exists, the value will be updated. If the key does not exist, the value will be inserted using the given key.

Python Dictionary values() Method

Returns a list of the values in the dictionary. The returned object is a dict_values object, which in Python is a "view object" - it cannot be changed, only viewed, iterated over, or converted to a list or other collection.

Python Dictionaries

A Python dictionary is a set of key-value pairs where the key is the index to the value. For example, think of a store where each item has a price:

The Python Dictionary ** unpack operator

When passing a dictionary to a function, the key-value pairs can be unpacked into keyword arguments in a function call where the dictionary keys match the parameter names of the function.