List comprehensions are mostly recreated with arrayfun/cellfun, but there's no dictionaryfun. What's a good way to port the following Python syntax?
{2*i: x-1 for i, x in enumerate([1, 2, 3]) if (x != 2 and i > 0)}
# {4: 2}
{i: ("a", x**2) for i, x in enumerate([1, np.array([2, 3])])}
# {0: ('a', 1), 1: ('a', array([4, 9]))}
{k: v**2 for k, v in dict(a=1, b=-2).items() if v > 0}
# {'a': 1}
So something nearly fully general, sparing nested comprehensions, value-dependent keys, key-dependent values, and ternary-conditional keys/values (v if v > 0 else v**2). Indexing is to remain 1-indexed.
I implemented dictionary comprehensions in MATLAB using the latest
dictionary. Typical syntax isIt also fully supports ternary conditionals:
via
ifelse(a, cond, b), implemented separately. Code & validation below.If there's better ways to do this, feel free to share.
py_dictcompifelse& validationAvailable at Github.