Andreina
Andreina

Reputation: 73

convert list of key/value strings into map python

Convert list of key/value strings into map. Assume that the list contains only strings and that each string has exactly one ':' .

Is the following code a good approach? Does anyone know of a more elegant solution to this?

>>> l = ['name:number']
>>> l = {x[:x.find(':')] : x[x.find(':')+1:] for x in l}
>>> print(l)
{'name': 'number'}

Upvotes: 0

Views: 307

Answers (1)

Ofer Sadan
Ofer Sadan

Reputation: 11922

An even simpler approach:

>>> l = ['name:number']
>>> dict(x.split(':') for x in l)
{'name': 'number'}

Upvotes: 1

Related Questions