Getting a few values out of dictionary with default different than None (Python) -


i don't quite this: accessing python dict 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 1 needs default different none?

i 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 , not economic tradeoff writing 2 d.get(key, 'mydefault') calls.

anything better (short of obvious solution of writing trivial utility function that)? esp. in python 3?

use collections.defaultdict:

>>> collections import defaultdict >>> d = defaultdict(lambda: 'mydefault', {'a':1, 'b':2}) >>> d['c'] 'mydefault' >>> map(d.get, ['a', 'c']) [1, none] >>> map(d.__getitem__, ['a', 'c']) [1, 'mydefault'] 

Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -