Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map list of strings containing key value to dict in Python?

My list contains the following elements:

>>> s = "foo a=b c=d e=f"
>>> s.split()
['set', 'a=b', 'c=d', 'e=f']
>>> splitted = s.split()
>>> splitted[1:]
['a=b', 'c=d', 'e=f']

Now I want to use map to get the following result:

[{'a': 'b'}, {'c': 'd'}, {'e': 'f'}]

I tried the following, but this gives me an IndexError:

>>> map(lambda x : dict((a[0], a[1]) for a in x.split('=')) , splitted[1:])

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
  File "<stdin>", line 1, in <genexpr>
IndexError: string index out of range
like image 278
John Doe Avatar asked Mar 08 '23 04:03

John Doe


2 Answers

You don't want to iterate over what you've split, just wrap that in an iterable, like a tuple:

>>> splitted
['a=b', 'c=d', 'e=f']
>>> [dict((x.split('='),)) for x in splitted]
[{'a': 'b'}, {'c': 'd'}, {'e': 'f'}]

I.E.

(x.split('='),)

Is a tuple with one element, the result of .spliting on the '=' sign.

Or using map and lambda:

>>> list(map(lambda x: dict((x.split('='),)), splitted))
[{'a': 'b'}, {'c': 'd'}, {'e': 'f'}]

I will say, this seems like a rather un-useful data-structure.

To be clear, your construction fails because you are iterating too deeply. The generator expression:

(a[0], a[1]) for a in x.split('=')

Is iterating over x.split('='), which in this case is always a list with two elements, length-1 strings, e.g. ['a','b'].

like image 65
juanpa.arrivillaga Avatar answered May 10 '23 16:05

juanpa.arrivillaga


You may create a simple list comprehension to achieve this. Here you need to split each string based on = and type-cast it to dict. For example:

>>> my_list = ['a=b', 'c=d', 'e=f']

>>> [dict([my_str.split('=')])  for my_str in my_list]
[{'a': 'b'}, {'c': 'd'}, {'e': 'f'}]

Here's the working working version of your solution using lambda:

#     actually you don't need to iterate here v
>>> list(map(lambda x : dict([[a for a in x.split('=')]]) , my_list))
[{'a': 'b'}, {'c': 'd'}, {'e': 'f'}]

This could be simplified as:

>>> list(map(lambda x : dict([x.split('=')]) , my_list))
[{'a': 'b'}, {'c': 'd'}, {'e': 'f'}]
like image 38
Moinuddin Quadri Avatar answered May 10 '23 14:05

Moinuddin Quadri