简体   繁体   中英

Creating a Dictionary from a List of 2-Tuples

I have a list of 2-tuples like this:

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

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

l.a #=> 1

So I tried this, but why does it fail?

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

This gives the error:

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

What am I doing wrong?

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

Why not just do this:

d = dict(l)

Also, to answer your question, your solution is failing because y (which is a 2-tuple) has no method update, since it's not a dict. Thankfully, what you're doing is built right in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM