Skip to content

Dict

Maps hashable objects to a value

Create

Create a dictionary

Action Code Details
Define empty dictionary
x = {}
Define with string keys and values
x = {'color': 'blue', 'size': 'large'}
Define with integer keys
x = {1: 'a', 2: 'b', 3: 'c'}
Generate from comprehension over list of keys
keys = ['a', 'b', 'c']
{key: key.upper() for key in keys}
Define from keys iterator and constant value v
dict.fromkeys(key_iter, v)
Define dynamically from iterators for keys and values
x = dict(zip(key_iter, value_iter))

Test

Action Code Details
Is dict or subclass
isinstance(x, dict)
Is dict but not subclass
type(x) is dict
Is empty
x
Is not empty
not x
Contains key k
k in x
Contains value v
v in x.values()
Contains value None
None in x.values()
Contains specific keys
{k1, k2}.issubset(x)
Contains keys keys
set(keys).issubset(x)
Contains specific values
{v1, v2}.issubset(x.values())
Contains values values
set(values).issubset(x.values())
Contains duplicate values
len(x) != len(set(x.values()))

Extract

Action Code Details
Number of key-value elements
len(x)
Hash
hash(frozenset(x.items()))
Keys
x.keys()
As dict_keys
Keys as list
list(x)
Keys as sorted list
sorted(x)
All keys with value v
[k for k in x if x[k] == v]
Values
x.values()
As dict_values
Values as list
list(x.values())
Values sorted by keys
[x[k] for k in sorted(x)]
Values from list of keys
[x[k] for k in keys_list]
Entries (as list of tuples)
x.items()
Value from key
x['color']
Throws an error if missing
Try get value from key
x.get('color')
Returns None if missing
Try get value from key, with default v if missing
x.get('color', v)
First key with value v
next(k for k in x if x[k] == v)
Get index of key k
list(x.keys()).index(k)

Update

Action Code Details
Update entry value
x['size'] = 'small'
Update entry, error if missing
?
?
Rename entry
x['new'] = x.pop('old')

Grow

Action Code Details
Add or update entry
x['size'] = 'small'
Add entry with value if it does not exist
x.setdefault('size', 'medium')

Shrink

Action Code Details
Remove all entries (clear)
x.clear()
Remove entry by key
del x['size']
Remove entries by keys
for k in keys: del x[k]
Remove entry by key, get value
x.pop('size')
Remove keys, get values
[x.pop(k) for k in keys]
Remove last-inserted entry, get value
x.popitem()

Combine

Instead of merging several dictionaries, consider using a ChainMap, which is often much faster.

Action Code Details
Merge with another dictionary
x |= y
Merge with another dictionary
x.update(y)

Derive

Action Code Details
Copy
x.copy()
Copy
dict(x)
Subset for keys
{k: x[k] for k in keys}
Error if a key is missing
Subset for keys with default v
{k: x.get(k, default=v) for k in keys}
Subset (intersection) for keys
{k: x[k] for k in x.keys() if k in keys}
Returns empty dict if all keys are missing
Subset except for keys
{k: x[k] for k in x.keys() if k not in keys}

Combine

Action Code Details
Merge dictionaries
z = x | y
Merge dictionaries
z = {**x, **y}

Convert

Action Code Details
List of key-value tuples
x.items()
JSON string
json.dumps(x)
JSON string, handle non-string entries
json.dumps(x, default = str)

Iterate

Action Code Details
Loop over keys
for key in x:
Loop over values
for value in x.values():
Loop over key-value pairs
for key, value in x.items():
More efficient than a key-based for-loop as each x[k] lookup requires recomputation of the hash for k

Show

Action Code Details
Pretty print
pprint.pprint(x)