Creating a dictionary from a list of 2 sets

I have a list of 2 tuples:

l = [('a', 1), ('b', 2)]

and I want to be able to map this to a dictionary object so that I can do something like

l.a #=> 1

So, I tried this, but why doesn't it work?

d = reduce(lambda y,x : y.update({x[0]:x[1]}),l,{})

This gives an error:

AttributeError: object "NoneType" has no attribute 'update'

What am I doing wrong?

+5
source share
2 answers
>>> l = [('a', 1), ('b', 2)]
>>> d = dict(l)
>>> d['a']
1 
+20
source

Why not just do it:

d = dict(l)

Also, to answer your question, your solution fails because y(which is a 2-tuple) does not update the method, since it is not a dict. Fortunately, what you do is built correctly.

+4

All Articles