Getting a few values out of dictionary with default different than None
(Python)
I don't quite like this: Accessing python dict with multiple key lookup
string
So:
In [113]: d = {'a':1, 'b':2}
In [114]: va, vb = map(d.get, ['a', 'b'])
In [115]: va, vb
Out[115]: (1, 2)
But:
In [116]: va, vb = map(d.get, ['a', 'X'])
In [117]: va, vb
Out[117]: (1, None)
What if one needs a default different than None?
I could use lambda:
In [118]: va, vb = map(lambda x: d.get(x) or 'MyDefault', ['a', 'c'])
In [119]: va, vb
Out[119]: (1, 'MyDefault')
But that's kind of convoluted and not very economic tradeoff for writing 2
d.get(key, 'MyDefault') calls.
Anything better (short of obvious solution of writing trivial utility
function for that)? Esp. in Python 3?
No comments:
Post a Comment