1

There is a list, which includes the following data,

a = ['key1=value1','key2=value2','key3=value3',...,'key100=value100']

I write the code below, which converts the list to one dict in one line,

b = dict((list(item.split('='))[0], list(item.split('='))[1]) for item in a

(My Python version is 2.6, which doesn't support dictionary comprehension.)

My question:
Is there a way to rewrite the code, which is more condense? e.g.,

b=dict(x,y) for item.split('=') in a       [WRONG]

I felt list(item.split('='))[0] and list(item.split('='))[1] is really cumbersome.

[Update]
@TigerhawkT3, the link Alternative to dict comprehension prior to Python 2.7 doesn't solve my problem, because my question is nothing with learning how to write dict comprehension prior to Python 2.7.

Community
  • 1
  • 1
Matt Elson
  • 4,177
  • 8
  • 31
  • 46
  • 2
    http://stackoverflow.com/questions/21069668/alternative-to-dict-comprehension-prior-to-python-2-7 – Maroun Jan 10 '16 at 09:47
  • 4
    Why not `dict([x.split('=') for x in a])`? – Henrik Andersson Jan 10 '16 at 09:49
  • 1
    Similar with Henriks': `b = dict(item.split("=") for item in a)`. Runs in python 2.7 not sure if 2.6 needs the `[]. Inspired from [here](http://stackoverflow.com/questions/186857/splitting-a-semicolon-separated-string-to-a-dictionary-in-python) – urban Jan 10 '16 at 09:53

1 Answers1

2

A dictionary can be initialized with an iterable, returning iterables with exactly two objects. This should do it:

d = dict([item.split('=', 1) for item in a])

Alternatively, you could use map():

d = dict(map(lambda item: item.split("=", 1), a))
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378