|
3 | 3 |
|
4 | 4 | '''Defines several functions that may be useful when working with dicts.''' |
5 | 5 |
|
| 6 | +from python_toolbox import cute_iter_tools |
| 7 | + |
6 | 8 |
|
7 | 9 | def filter_items(d, condition, force_dict_type=None): |
8 | 10 | ''' |
@@ -67,9 +69,31 @@ def reverse_with_set_values(d): |
67 | 69 | reverse_with_set_values({1: 2, 3: 4, 'meow': 2}) == \ |
68 | 70 | {2: set([1, 'meow']), 4: set([3])} |
69 | 71 | |
| 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. |
70 | 75 | ''' |
| 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 | + |
71 | 95 | new_dict = {} |
72 | | - for key, value in d.iteritems(): |
| 96 | + for key, value in fixed_dict.iteritems(): |
73 | 97 | if value not in new_dict: |
74 | 98 | new_dict[value] = [] |
75 | 99 | new_dict[value].append(key) |
|
0 commit comments