list to dict?

Raymond Hettinger vze4rx4y at verizon.net
Wed Mar 12 05:00:57 CET 2003


> > Say I have a list, and it looks something like
> > ["name=matt","sex=male","age=24"] (etcetera) and I wanted to convert
> > it to a dictionary: {'name': 'matt', 'sex': 'male', 'age': '24'}

Try this:

>>> s = ["name=matt","sex=male","age=24"]
>>> dict(map(str.split, s, '='*len(s)))
{'age': '24', 'name': 'matt', 'sex': 'male'}


Or for clarity:

>>> d = {}
>>> for pair in s:
             key, value = pair.split("=")
             d[key] = value




Raymond Hettinger






More information about the Python-list mailing list