List to dict conversion

W

Wujek

Hi!

From list:['key1:val1', 'key2:val2']

I want dict:{'key2': 'val2', 'key1': 'val1'}

Is there any better (faster, simplier, prettier?) solution than this?.... spl=line.split(':')
.... d[spl[0]] = spl[1]


Regards.
 
G

Gerrit Holl

Hi!

From list:['key1:val1', 'key2:val2']

I want dict:{'key2': 'val2', 'key1': 'val1'}

Is there any better (faster, simplier, prettier?) solution than this?... spl=line.split(':')
... d[spl[0]] = spl[1]
</quote>

How about:
dict([s.split(':') for s in l])

Don't know if it's faster, simplier or prettier, but I find it easier to read.
This may not be the case if you aren't familiar with list comprehensions, though.

Gerrit.
 
A

Alex Martelli

Wujek said:
Hi!

From list:['key1:val1', 'key2:val2']

I want dict:{'key2': 'val2', 'key1': 'val1'}

Is there any better (faster, simplier, prettier?) solution than this?... spl=line.split(':')
... d[spl[0]] = spl[1]

d = dict([ x.split(':') for x in l ])

should work just the same way as your loop -- perhaps marginally
faster (try both with timeit.py, of course, if it DOES matter...!),
and "simpler" and "prettier" are in the eyes of the beholders.


Alex
 
W

Wujek

Gerrit said:
How about:
dict([s.split(':') for s in l])

Don't know if it's faster, simplier or prettier, but I find it easier to read.
This may not be the case if you aren't familiar with list comprehensions, though.

No, I like it. Thank you (and Alex too).

Regards.
 
E

Emile van Sebille

Wujek said:
Hi!

From list:['key1:val1', 'key2:val2']

I want dict:{'key2': 'val2', 'key1': 'val1'}

Guessing that this may have been read from a file, you may also be
interested in looking at ConfigParser. From the module:

DESCRIPTION
A setup file consists of sections, lead by a "[section]" header,
and followed by "name: value" entries, with continuations and such in
the style of RFC 822.
 
W

Wujek

Emile said:
Guessing that this may have been read from a file, you may also be
Indeed.

interested in looking at ConfigParser. From the module:

Data will be read from number of small files. ConfigParser is too big
gun for this fly, I think. This oneliner (from previous posts in this
thread) is much better for this task.

Regards.
 

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

Forum statistics

Threads
474,164
Messages
2,570,898
Members
47,440
Latest member
YoungBorel

Latest Threads

Top