Okay, the core logic of your existing function is actually already well-suited to handle dictionaries as values, because Python's in operator for lists will correctly compare dictionaries for equality.
The main changes needed are:
- Update the type hint for
value from str to Any (or dict if you only want to allow dicts, but Any makes it more versatile).
- Update the docstring to reflect this.
- Optionally, rename the parameter
value to something like item_to_add for more generality if you wish, but value is fine.
Here's the refactored function:
from typing import Any, Dict, List, Hashable # For type hinting
def add_unique_item_to_list_in_dict(
dictionary: Dict[Hashable, List[Any]],
key: Hashable,
item_to_add: Any
) -> bool:
"""
Add a unique item (which can be a dictionary or any other type)
to the specified dictionary's key list.
Args:
dictionary (dict): The dictionary to modify.
key (Hashable): The key whose list will be modified.
The key must be hashable (e.g., str, int, tuple).
item_to_add (Any): The item to add to the list. This item will be
checked for uniqueness before adding.
Returns:
bool: True if item_to_add was added, False if it already exists in the list.
"""
# Ensure the key exists with an empty list if it doesn't
# dictionary.setdefault(key, []) is a more Pythonic way to do this:
if key not in dictionary:
dictionary[key] = []
# Or, using setdefault:
# dictionary.setdefault(key, [])
# Check if item_to_add is not already in the list
# This works for simple types, lists, tuples, and dictionaries.
if item_to_add not in dictionary[key]:
dictionary[key].append(item_to_add)
return True
return False
# --- Example Usage ---
if __name__ == "__main__":
acq_wrk_base_docker_compose = {}
HAS_MQTT_NETWORK_BRIDGE = "mqtt_network" # Example constant
OTHER_NETWORK_NAME = "internal_comm"
print("Initial dictionary:", acq_wrk_base_docker_compose)
# Test Case 1: Add a new dictionary value
added1 = add_unique_item_to_list_in_dict(
dictionary=acq_wrk_base_docker_compose,
key="networks",
item_to_add={HAS_MQTT_NETWORK_BRIDGE: None},
)
print(f"\nAdded '{HAS_MQTT_NETWORK_BRIDGE}': {added1}")
print("Dictionary after first add:", acq_wrk_base_docker_compose)
# Expected: {'networks': [{'mqtt_network': None}]}
# Test Case 2: Try to add the same dictionary value again
added2 = add_unique_item_to_list_in_dict(
dictionary=acq_wrk_base_docker_compose,
key="networks",
item_to_add={HAS_MQTT_NETWORK_BRIDGE: None},
)
print(f"\nAdded '{HAS_MQTT_NETWORK_BRIDGE}' again: {added2}")
print("Dictionary after second add (should be unchanged):", acq_wrk_base_docker_compose)
# Expected: {'networks': [{'mqtt_network': None}]} (no change, added2 is False)
# Test Case 3: Add a different dictionary value to the same key
added3 = add_unique_item_to_list_in_dict(
dictionary=acq_wrk_base_docker_compose,
key="networks",
item_to_add={OTHER_NETWORK_NAME: {"driver": "bridge"}},
)
print(f"\nAdded '{OTHER_NETWORK_NAME}': {added3}")
print("Dictionary after third add:", acq_wrk_base_docker_compose)
# Expected: {'networks': [{'mqtt_network': None}, {'internal_comm': {'driver': 'bridge'}}]}
# Test Case 4: Add a value to a new key
added4 = add_unique_item_to_list_in_dict(
dictionary=acq_wrk_base_docker_compose,
key="volumes",
item_to_add={"my_data": None},
)
print(f"\nAdded 'my_data' volume: {added4}")
print("Dictionary after fourth add:", acq_wrk_base_docker_compose)
# Expected: {'networks': [...], 'volumes': [{'my_data': None}]}
# Test Case 5: Add a simple string value (to show versatility)
added5 = add_unique_item_to_list_in_dict(
dictionary=acq_wrk_base_docker_compose,
key="services",
item_to_add="web_server",
)
print(f"\nAdded 'web_server' service: {added5}")
print("Dictionary after fifth add:", acq_wrk_base_docker_compose)
# Expected: {'networks': [...], 'volumes': [...], 'services': ['web_server']}
# Test Case 6: Add another simple string value to the same list
added6 = add_unique_item_to_list_in_dict(
dictionary=acq_wrk_base_docker_compose,
key="services",
item_to_add="database",
)
print(f"\nAdded 'database' service: {added6}")
print("Dictionary after sixth add:", acq_wrk_base_docker_compose)
# Test Case 7: Try to add an existing string value
added7 = add_unique_item_to_list_in_dict(
dictionary=acq_wrk_base_docker_compose,
key="services",
item_to_add="web_server",
)
print(f"\nAdded 'web_server' service again: {added7}")
print("Dictionary after seventh add (should be unchanged):", acq_wrk_base_docker_compose)
Explanation of Changes and Why It Works:
item_to_add: Any: The type hint for item_to_add is changed to Any. This signifies that the function can now accept items of any type, including dictionaries, strings, integers, lists, etc.
dictionary: Dict[Hashable, List[Any]]:
Hashable for the key type means the dictionary keys can be strings, numbers, tuples of hashable items, etc., but not mutable types like lists or other dictionaries. This is a standard requirement for dictionary keys.
List[Any] for the dictionary value type means each value associated with a key is a list that can contain items of any type.
if item_to_add not in dictionary[key]:: This line is the core of the uniqueness check.
- When
item_to_add is a dictionary (e.g., {HAS_MQTT_NETWORK_BRIDGE: None}) and dictionary[key] is a list of dictionaries (e.g., [{'some_other_network': True}]), Python iterates through the list.
- For each element in the list, it checks if
item_to_add == element.
- Dictionary comparison (
==) in Python checks for "value equality": two dictionaries are equal if they have the same keys and the corresponding values for each key are equal. The order of keys does not matter for equality.
The function is now more generic and directly supports your use case with dictionary values without needing a completely new function. I've renamed it to add_unique_item_to_list_in_dict to better reflect its more general nature, but you can keep your original name if you prefer. The parameter value was also changed to item_to_add for the same reason.