Andriy Kornatskyy avatar Andriy Kornatskyy committed cad00c9

Added map_keys, map_values and sorted_items to collections.

Comments (0)

Files changed (1)

src/wheezy/core/collections.py

 import struct
 import zlib
 
+from operator import itemgetter
+
 from wheezy.core.comp import defaultdict
 from wheezy.core.comp import ntob
 
             yield chunk
     yield gzip.flush()
     yield struct.pack('<2L', crc, size & MAX_INT)
+
+
+def map_keys(function, dictionary):
+    """ Apply `function` to every key of `dictionary` and return
+        a dictionary of the results.
+
+        >>> d = {'1': 1, '2': 2}
+        >>> sorted_items(map_keys(lambda key: 'k' + key, d))
+        [('k1', 1), ('k2', 2)]
+    """
+    return dict([(function(key), value) for key, value in dictionary.items()])
+
+
+def map_values(function, dictionary):
+    """ Apply `function` to every value of `dictionary` and return
+        a dictionary of the results.
+
+        >>> d = {'1': 1, '2': 2}
+        >>> sorted_items(map_values(lambda value: 2 * value, d))
+        [('1', 2), ('2', 4)]
+    """
+    return dict([(key, function(value)) for key, value in dictionary.items()])
+
+
+def sorted_items(dictionary):
+    """ Returns `dictionary` items sorted by key.
+
+        >>> d = {'1': 1, '2': 2}
+        >>> sorted_items(d)
+        [('1', 1), ('2', 2)]
+    """
+    return sorted(dictionary.items(), key=itemgetter(1))
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.