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
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 .split
ing 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']
.
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'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With