From 37b556ded8b086a7cb6381e3f796e1b7ba5e7789 Mon Sep 17 00:00:00 2001 From: wirawan Date: Mon, 8 Feb 2010 19:58:44 +0000 Subject: [PATCH] * Added dict_slice, a slicing tool returning a subset of a given dict (or other dict-like object). --- sugar.py | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/sugar.py b/sugar.py index 2b151df..cd9b71f 100644 --- a/sugar.py +++ b/sugar.py @@ -1,6 +1,6 @@ #!/usr/bin/ipython -pylab # -# $Id: sugar.py,v 1.1 2010-01-22 18:46:50 wirawan Exp $ +# $Id: sugar.py,v 1.2 2010-02-08 19:58:44 wirawan Exp $ # # Created: 20100121 # Wirawan Purwanto @@ -10,6 +10,7 @@ # Beware of their caveats! # # +import sys def ifelse(cond, trueval, *args): """An alternative to python's own ternary operator, but with multiple @@ -29,3 +30,25 @@ def ifelse(cond, trueval, *args): if i < len(args): return args[i] return None # Fallback solution: "None" + + +if sys.version_info < (2,4): + def sorted(List): + rslt = [ L for L in List ] # == L.copy() + rslt.sort() + return rslt +else: + #print dir(globals()) + sorted = sorted + +#print dir(globals()) + +def dict_slice(Dict, *keys): + """Returns a shallow copy of the subset of a given dict (or an otherwise + hashable object) with a given set of keys. + + Example: if d = {'abc': 12, 'def': 7, 'ghi': 32, 'jkl': 98 } + then dict_slice(d, 'abc', 'ghi') will yield {'abc': 12, 'ghi': 32 } + """ + return dict([ (k, Dict[k]) for k in keys ]) +