Python Language Dictionary

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

Internal

Overview

A dictionary is a mutable collection of key-value pairs. The pairs can be accessed and modified. Each key is unique within the key set, and can be an instance of any immutable type: boolean, integer, float, tuple, string, etc., including None. There is a difference between a key that does not exist in the dictionary and a key that has been explicitly set to None - see Access with [] Syntax for more details. In other programming languages, the same data structure is referred to as "associative array" or "hash tables" or "hash maps".

The same underlying dictionary data structure can be referred by multiple variable names, which can be assigned with =, and if the structure is changed, the change will be reflected if any of the variables is used for access. To avoid this, make a copy of the dictionary with copy().

Dictionary type()

The function type() applied to a dictionary returns: <class 'dict'>

To check whether an instance is a dictionary:

i = ...
if type(i) is dict:
  ...

For dict subclasses:

i = ...
if isinstance(i, dict):
  ...

Key Discussion

The keys 1 and True are equivalent. Why?

Create a Dictionary

A new dictionary instance is declared using the {...} syntax. The curly braces are placed around comma-separated key: value pairs. The dictionary can be empty

d = {}

or it can be populated with values:

d = {'a': 'b', 1: 2}

It is good form to insert a space after :. A comma is tolerated after the last pair.

Converting Other Data Structures to a Dictionary

Any two-value sequences can be converted into a dictionary using the dict() function.

Examples:

# list of lists
l = [['a', 'b'], ['c', 'd'], ['e', 'f']]
d = dict(l) # will create {'a': 'b', 'c': 'd', 'e': 'f'}

# list of tuples
l = [('a', 'b'), ('c', 'd'), ('e', 'f')]
d = dict(l) # will create {'a': 'b', 'c': 'd', 'e': 'f'}

# tuple of two-item lists
l = (['a', 'b'], ['c', 'd'], ['e', 'f'])
d = dict(l) # will create {'a': 'b', 'c': 'd', 'e': 'f'}

# list of two-character strings
l = ['ab', 'cd', 'ef']
d = dict(l) # will create {'a': 'b', 'c': 'd', 'e': 'f'}

# tuple of two-character strings
l = ('ab', 'cd', 'ef')
d = dict(l) # will create {'a': 'b', 'c': 'd', 'e': 'f'}

Access a Dictionary

Test for Empty Dictionary

Empty dictionaries evaluate to False:

d1 = {}
if not d1:
    print("dictionary is empty")

Size of a Dictionary

The number of key is given by the len() function:

d = {...}
print(len(d))

Access Individual Elements

Individual dictionary elements can be accessed with the [] syntax or with the get() function.

Access with [] Syntax

The [] syntax can only be used with keys that exist in the dictionary:

d = {'a': 'b'}
print(d['a'])

An attempt to access an inexistent key will throw a KeyError exception. To avoid the exception, use get() instead, or test the existence of the key first.

However, a key can be explicitly set to None, and in this case, square bracket access to the key will return None:

d = {'a': None}
assert d['a'] is None

get() Function

The get() will return the associated value, or None if the key does not exist.

d = {'a': 'b'}
print(d.get('a')) # will display 'a'
print(d.get('no-such-key')) # will display None

The get() function allows for a second argument which will be returned instead of None in case the key does not exist:

d = {}
print(d.get('no-such-key', 'alternative')) # will display "alternative"

Safely Navigate a Complex Data Structure

Suggestions on how to safely recursively navigate a complex data structure:

Safely Navigate a Complex Data Structure

Test the Existence of a Key

The existence of the key can be tested with in:

if 'some-key' in d:
  print("key exists")

The non-existence is tested with this idiom:

if 'some-key' not in d:
  print("key does not exist")

get() can also be used:

if d.get('some-key') is not None:
  print("key exists")

Get All Keys

d = {'a': 'b', 'c': 'd'}
print(d.keys())

In Python 3, the keys() will return a dict_keys(), which is an iterable view of keys. This is useful with large dictionaries because the runtime does not use the time and the memory to create and store a list that might not be used. In case you need a list, use list() to wrap the result of keys().

list(d.keys())

Get All Values

d = {'a': 'b', 'c': 'd'}
print(d.values())

In Python 3, the values() will return a dict_values(), which is an iterable view of values. This is useful with large dictionaries because the runtime does not use the time and the memory to create and store a list that might not be used. In case you need a list, use list() to wrap the result of values().

list(d.values())

Get All Key-Value Pairs

d = {'a': 'b', 'c': 'd'}
print(d.items())

In Python 3, the items() will return a dict_items(), which is an iterable view of items. This is useful with large dictionaries because the runtime does not use the time and the memory to create and store a list that might not be used.

In case you need a list, use list() to wrap the result of items(). The list contains tuples of key and values.

for i in list(d.items()):
    print('key:', i[0])
    print('value:', i[1])

Modify a Dictionary

Modify Individual Elements

Modification with [] Syntax

Individual elements can be modified with the [] syntax. If the key does not exist, the key-value pair will be added to the dictionary. If the key exists, the associated value will be updated:

d = {}
d['a'] = 'b'
print(d['a']) # will display "a"
d['a'] = 'c'
print(d['a']) # will display "c"

Delete Individual Element

d = {'a': 'b', 'c': 'd'}
del d['a']
print(d) # will display {'c': 'd'}

Note that if the key being deleted does not exist, the [] syntax will throw an KeyError exception.

Delete All Items

Use the clear() function:

d = {...}
d.clear()

Combine Dictionaries

Two dictionaries can be combined with update():

d1 = {'a': 'b'}
d2 = {'c': 'd'}
d1.update(d2) # d1 will become {'a': 'b', 'c': 'd'}, d2 will remain unchanged

If the same key exists in both dictionaries, the value associated with the key in the second dictionary will take precedence.

Copy a Dictionary

d1 = {'a': 'b'}
d2 =d1.copy()
d1['a'] = 'c'
print(d1['a']) # will display 'c'
print(d2['a']) # will display 'b'