Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 27 additions & 3 deletions benedict/core/invert.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,34 @@ def _invert_list(


def invert(d: MutableMapping[_K, _V], flat: bool = False) -> MutableMapping[Any, Any]:
new_dict = clone(d, empty=True)
# Imported here to avoid a circular import at module load time.
from benedict.dicts.keypath import keypath_util

# Collect the inverted pairs in a plain dict first: the values become the
# keys of the result, so they must be handled as literal keys instead of
# keypaths (issue #671). Otherwise a value like "one.two" would silently
# create a nested mapping and overwrite unrelated groups.
inverted: dict[Any, Any] = {}
for key, value in d.items():
if type_util.is_list_or_tuple(value):
_invert_list(new_dict, key, value, flat)
_invert_list(inverted, key, value, flat)
else:
_invert_item(new_dict, key, value, flat)
_invert_item(inverted, key, value, flat)

new_dict = clone(d, empty=True)
separator = getattr(new_dict, "_keypath_separator", None)
for key, value in inverted.items():
# Values that would be reinterpreted as keypaths cannot be represented
# as literal keys in a keypath-aware dict, so reject them explicitly.
if (
separator
and type_util.is_string(key)
and keypath_util.parse_keys(key, separator) != [key]
):
raise ValueError(
f"invert() cannot use {key!r} as a key because it would be "
f"interpreted as a keypath, not a literal key."
)
new_dict[key] = value

return new_dict
20 changes: 20 additions & 0 deletions tests/core/test_invert.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,23 @@ def test_invert_with_tuple_values(self) -> None:
],
}
self.assertEqual(o, r)

def test_invert_keeps_literal_values_as_keys(self) -> None:
from benedict import benedict

b = benedict({"a": "foo", "b": "foo bar"})
self.assertEqual(b.invert(), {"foo": ["a"], "foo bar": ["b"]})

def test_invert_rejects_dotted_values(self) -> None:
from benedict import benedict

b = benedict({"a": "one.two"})
with self.assertRaises(ValueError):
b.invert()

def test_invert_rejects_indexed_values(self) -> None:
from benedict import benedict

b = benedict({"a": "foo", "b": "foo[0]"})
with self.assertRaises(ValueError):
b.invert(flat=True)