How to turn a list of tuples into a dictionary?

M

mrstephengross

Let's say I've got a list of tuples, like so:

( ('a', '1'), ('b', '2'), ('c', '3')

And I want to turn it into a dictionary in which the first value of
each tuple is a key and the second value is a value, like so:

{ 'a' -> '1', 'b' -> '2', 'c' -> '3' }

Is there a way to do this with a single line of code? Currently, I'm
doing it like this:

tuples = ( ('a', '1'), ('b', '2'), ('c', '3')
d = {}
for option,value in tuples: d[option] = value

Thanks,
--Steve
 
C

castironpi

Let's say I've got a list of tuples, like so:

  ( ('a', '1'), ('b', '2'), ('c', '3')

And I want to turn it into a dictionary in which the first value of
each tuple is a key and the second value is a value, like so:

  { 'a' -> '1', 'b' -> '2', 'c' -> '3' }

Is there a way to do this with a single line of code? Currently, I'm
doing it like this:

  tuples =   ( ('a', '1'), ('b', '2'), ('c', '3')
  d = {}
  for option,value in tuples:  d[option] = value

Thanks,
--Steve

I'd hand-code it manually, by linking a C extension. Or
dict( iterable ).

http://www.python.org/doc/current/lib/built-in-funcs.html#l2h-21
 
D

D'Arcy J.M. Cain

Let's say I've got a list of tuples, like so:

( ('a', '1'), ('b', '2'), ('c', '3')

And I want to turn it into a dictionary in which the first value of
each tuple is a key and the second value is a value, like so:

{ 'a' -> '1', 'b' -> '2', 'c' -> '3' }

Is there a way to do this with a single line of code? Currently, I'm
doing it like this:

tuples = ( ('a', '1'), ('b', '2'), ('c', '3')
d = {}
for option,value in tuples: d[option] = value

How about this?
d = dict(tuples)
 
C

castironpi

Aha! I hadn't realized it could be so simple.

--Steve

In terms of a metric for code, 'And runs in a single line!' may be a
bit deceptive. [Counterexample snipped.] Absent repeating the line
d= dict( tuples ) verbatim, how does:

identifiers: 3
- func. calls: 1
-- builtins: 1
-- call depth: 1
- assign't: 1
- variable: 1
nesting depth: 1
- parenthesis: 1
- control flow: 0
if statements: 0
- elifs: 0
- elses: 0
call tree: 0
- max. breadth: 1
-- per scope: 1
- max. depth: 1
-- per scope: 1

sound?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top