dicts
Common functions for working with dictionaries.
filter_dict(d, filter_keys, include=False)
Given a dictionary, return a new dictionary either including or excluding keys in a given filter
set.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
d |
dict
|
A dictionary to filter. |
required |
filter_keys |
Union[set, list]
|
A list or set of keys to either include or exclude. |
required |
include |
bool
|
Determine whether to return a dictionary including or excluding keys in |
False
|
Returns:
Type | Description |
---|---|
dict
|
A filtered dictionary. |
Examples:
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> filter_dict(d, {'a', 'b'})
{'c': 3}
>>> filter_dict(d, {'a', 'b'}, include=True)
{'a': 1, 'b': 2}
Source code in src/nhssynth/common/dicts.py
flatten_dict(d)
Flatten a dictionary by recursively combining nested keys into a single dictionary until no nested keys remain.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
d |
dict[str, Any]
|
A dictionary with potentially nested keys. |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A flattened dictionary. |
Raises:
Type | Description |
---|---|
ValueError
|
If duplicate keys are found in the flattened dictionary. |
Examples:
Source code in src/nhssynth/common/dicts.py
get_key_by_value(d, value)
Find the first key in a dictionary with a given value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
d |
dict
|
A dictionary to search through. |
required |
value |
Any
|
The value to search for. |
required |
Returns:
Type | Description |
---|---|
Union[Any, None]
|
The first key in |
Examples: