Skip to content

Commit a03fb08

Browse files
committed
-
1 parent cc421ae commit a03fb08

File tree

3 files changed

+52
-6
lines changed

3 files changed

+52
-6
lines changed

source_py3/python_toolbox/dict_tools.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,4 +141,32 @@ def get_sorted_values(d, key=None):
141141
'''
142142
kwargs = {'key': key,} if key is not None else {}
143143
return get_tuple(d, sorted(d.keys(), **kwargs))
144+
145+
146+
def reverse(d):
147+
'''
148+
Reverse a `dict`, creating a new `dict` where keys and values are switched.
149+
150+
Example:
151+
152+
>>> reverse({'one': 1, 'two': 2, 'three': 3})
153+
{1: 'one', 2: 'two', 3: 'three'})
154+
155+
This function requires that:
156+
157+
1. The values will be distinct, i.e. no value will appear more than once.
158+
2. All the values be hashable.
159+
160+
'''
161+
new_d = {}
162+
for key, value in d.items():
163+
if value in new_d:
164+
raise Exception(
165+
"Value %s appeared twice! Once with a key of %s and then "
166+
"again with a key of %s. This function is intended only for "
167+
"dicts with distinct values." % (value, key, new_d[value])
168+
)
169+
new_d[value] = key
170+
return new_d
171+
144172

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
11
# Copyright 2009-2015 Ram Rachum.
22
# This program is distributed under the MIT license.
33

4-
'''Test package for `dict_tools.devour_items`.'''
4+
from python_toolbox import cute_testing
55

66
from python_toolbox import dict_tools
77

88

9+
10+
911
def test():
10-
'''Test the basic workings of `devour_items`.'''
11-
my_dict = {1: 2, 3: 4, 5: 6,}
12-
assert set(dict_tools.devour_items(my_dict)) == {(1, 2), (3, 4), (5, 6)}
13-
assert not my_dict
14-
12+
assert dict_tools.reverse({'one': 1, 'two': 2, 'three': 3}) == \
13+
{1: 'one', 2: 'two', 3: 'three'}
14+
assert dict_tools.reverse({}) == {}
15+
with cute_testing.RaiseAssertor():
16+
dict_tools.reverse({1: 0, 2: 0})
17+
with cute_testing.RaiseAssertor():
18+
dict_tools.reverse({1: []})
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Copyright 2009-2015 Ram Rachum.
2+
# This program is distributed under the MIT license.
3+
4+
'''Test package for `dict_tools.devour_items`.'''
5+
6+
from python_toolbox import dict_tools
7+
8+
9+
def test():
10+
'''Test the basic workings of `devour_items`.'''
11+
my_dict = {1: 2, 3: 4, 5: 6,}
12+
assert set(dict_tools.devour_items(my_dict)) == {(1, 2), (3, 4), (5, 6)}
13+
assert not my_dict
14+

0 commit comments

Comments
 (0)