Python lamba function to convert to a dictionary? -
i having list of dictionary representation follows:
a = [{'score': 300, 'id': 3}, {'score': 253, 'id': 2}, {'score': 232, 'id': 1}]
i new python , need python lambda function through output :
dict = [{3:300}, {2:253}, {1:232}]
so can find value given key
>>> print dict[3] >>> 300
i appreciate on this.
- don't use
dict
variable name, because shadow builtin type namedict
; {3, 300}
not dictionary,{3:300}
is;
you can use dict comprehension:
in [6]: dic = {d['id']: d['score'] d in a} in [7]: dic out[7]: {1: 232, 2: 253, 3: 300}
or dict constructor @jon mentioned backward compatibility since dict-comp available on py2.7+ :
in [12]: import operator ...: dict(map(operator.itemgetter('id', 'score'), a)) out[12]: {1: 232, 2: 253, 3: 300}
Comments
Post a Comment