[Tutor] convert to dict

Karl Pflästerer sigurd at 12move.de
Tue Apr 27 12:18:09 EDT 2004

On 27 Apr 2004, Larry Blair <- lbblair at adaptisinc.com wrote:

> I have a string (below) that I want to convert to a dictionary. I think I
> can do it with a for loop and using split but just don't quite have the
> skills to manipulate the data. I am getting the data from a text properties
> file I read into the program.

> lb = ['TEMP01.DBF : 1024', 'TEMP02.DBF : 1024', 'TEMP03.DBF : 1024',
> 'TEMP04.DBF : 1024', 'TEMP05.DBF : 1024', 'TEMP06.DBF : 1024']

Using a for loop and splitting the data is one approach.

dic = {}
for kv in lb:
    key, val = kv.split(':')
    dic[key] = val

You initialize an empty dictionary, iterate over the list and split the
entries with split(':').

A bit shorter (but maybe less clear):

dic = {}
for kv in lb:
    dic.setdefault(* kv.split(':'))

setdefault() sets dic[key] =value if key is not already in dic and
returns value.  The `*' splices the list in the argument list; that
means it takes away the outermost pair of brackets of the list (or
parens of a tuple).  So f(* [a, b]) is the same as f(a, b).  It's nice
but if you just start to use Python you shouldn't maybe use it too

If you like it even shorter you could use a list comprehension (but it
uses more memory)

dic = dict([kv.split(':') for kv in lb])

Here you build a list of lists; each of the inner lists has two entries
where the first acts as key and the second as value in the dictionary.

So pick your favorite.

Please do *not* send copies of replies to me.
I read the list

More information about the Tutor mailing list