Skip to content

Commit 2b8d346

Browse files
committed
-
1 parent 13b86a4 commit 2b8d346

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

python_toolbox/dict_tools.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33

44
'''Defines several functions that may be useful when working with dicts.'''
55

6+
from python_toolbox import cute_iter_tools
7+
68

79
def filter_items(d, condition, force_dict_type=None):
810
'''
@@ -67,9 +69,31 @@ def reverse_with_set_values(d):
6769
reverse_with_set_values({1: 2, 3: 4, 'meow': 2}) == \
6870
{2: set([1, 'meow']), 4: set([3])}
6971
72+
Instead of a dict you may also input a tuple in which the first item is an
73+
iterable and the second item is either a key function or an attribute name.
74+
A dict will be constructed from these and used.
7075
'''
76+
### Pre-processing input: #################################################
77+
# #
78+
if hasattr(d, 'items'): # `d` is a dict
79+
fixed_dict = d
80+
else: # `d` is not a dict
81+
assert cute_iter_tools.is_iterable(d) and len(d) == 2
82+
iterable, key_function_or_attribute_name = d
83+
assert cute_iter_tools.is_iterable(iterable)
84+
if callable(key_function_or_attribute_name):
85+
key_function = key_function_or_attribute_name
86+
else:
87+
assert isinstance(key_function_or_attribute_name, basestring)
88+
key_function = \
89+
lambda key: getattr(key, key_function_or_attribute_name)
90+
91+
fixed_dict = dict((key, key_function(key)) for key in iterable)
92+
# #
93+
### Finished pre-processing input. ########################################
94+
7195
new_dict = {}
72-
for key, value in d.iteritems():
96+
for key, value in fixed_dict.iteritems():
7397
if value not in new_dict:
7498
new_dict[value] = []
7599
new_dict[value].append(key)

test_python_toolbox/test_dict_tools/test_reverse_with_set_values.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,12 @@
99
def test():
1010
'''Test the basic workings of `reverse_with_set_values`.'''
1111
assert dict_tools.reverse_with_set_values({1: 2, 3: 4, 'meow': 2}) == \
12-
{2: set([1, 'meow']), 4: set([3])}
12+
{2: set([1, 'meow']), 4: set([3])}
13+
14+
def test_iterable_input():
15+
assert dict_tools.reverse_with_set_values((range(1, 5), str)) == \
16+
{'1': set([1]), '2': set([2]), '3': set([3]), '4': set([4]),}
17+
18+
assert dict_tools.reverse_with_set_values(([1, 2+3j, 4, 5-6j], 'imag')) \
19+
== {0: set([1, 4]), 3: set([2+3j]), -6: set([5-6j])}
20+

0 commit comments

Comments
 (0)