Skip to content

Commit 2eb8ecb

Browse files
committed
ENH: little helper utility to find dicts intersection
1 parent 64569f1 commit 2eb8ecb

File tree

2 files changed

+30
-7
lines changed

2 files changed

+30
-7
lines changed

heudiconv/tests/test_utils.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,20 @@
55
import mock
66

77
from heudiconv.utils import (
8-
get_known_heuristics_with_descriptions,
8+
create_tree,
9+
get_datetime,
10+
get_dicts_intersection,
911
get_heuristic_description,
10-
load_heuristic,
12+
get_known_heuristics_with_descriptions,
1113
json_dumps_pretty,
14+
JSONDecodeError,
15+
load_heuristic,
1216
load_json,
13-
create_tree,
17+
remove_prefix,
18+
remove_suffix,
1419
save_json,
1520
update_json,
16-
get_datetime,
17-
remove_suffix,
18-
remove_prefix,
19-
JSONDecodeError)
21+
)
2022

2123
import pytest
2224
from .utils import HEURISTICS_PATH
@@ -170,3 +172,10 @@ def test_remove_prefix():
170172
assert remove_prefix(s, '') == s
171173
assert remove_prefix(s, 'foo') == s
172174
assert remove_prefix(s, 'jason') == '.bourne'
175+
176+
177+
def test_get_dicts_intersection():
178+
assert get_dicts_intersection([]) == {}
179+
assert get_dicts_intersection([{"a": 1}]) == {"a": 1}
180+
assert get_dicts_intersection([{"a": 1}, {"b": 2}]) == {}
181+
assert get_dicts_intersection([{"a": 1}, {"a": 1, "b": 2}]) == {"a": 1}

heudiconv/utils.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -645,3 +645,17 @@ def remove_prefix(s, pre):
645645
if pre and s.startswith(pre):
646646
return s[len(pre):]
647647
return s
648+
649+
650+
def get_dicts_intersection(recs: list[dict]) -> dict:
651+
"""Given a list of dictionaries, return a dict of key:values which are the same
652+
across all entries
653+
"""
654+
if not recs:
655+
return {}
656+
common_keys = recs[0].copy()
657+
for r in recs[1:]:
658+
for k, v in common_keys.copy().items():
659+
if k not in r or r[k] != v:
660+
common_keys.pop(k)
661+
return common_keys

0 commit comments

Comments
 (0)