Reputation:
I have the following output from a code I ran on Python:
T1 = [{0: 0}, {15: 3}, {19: 1}, {20: 1}, {0: 0}]
I want to extract the keys and values from each object respectively. For T1, I would thus have:
P1 = [0,15,19,20,0]
D1 = [0, 3, 1,1,0]
What would be the best way to code it?
Thanks in advance,
Upvotes: 2
Views: 721
Reputation: 46899
this should work:
T1 = [{0: 0}, {15: 3}, {19: 1}, {20: 1}, {0: 0}]
P1 = [next(iter(dct)) for dct in T1]
D1 = [next(iter(dct.values())) for dct in T1]
you take the first element (next
) of an iterator over the keys (iter(dct)
) or an interator over the values (iter(dct.values()
).
this will not create any unnecessary lists.
or in one go (note: these return tuples
not lists
):
P1, D1 = zip(*(next(iter(dct.items())) for dct in T1))
or (using parts of deceze's answer):
from itertools import chain
P1, D1 = zip(*chain.from_iterable(dct.items() for dct in T1))
Upvotes: 1
Reputation: 522402
Sounds like a good case for chain.from_iterable
:
>>> from itertools import chain
>>> from operator import methodcaller
>>> T1 = [{0: 0}, {15: 3}, {19: 1}, {20: 1}, {0: 0}]
>>> list(chain.from_iterable(T1))
[0, 15, 19, 20, 0]
>>> list(chain.from_iterable(map(methodcaller('values'), T1)))
[0, 3, 1, 1, 0]
A dictionary when iterated over yields its keys; chain.from_iterable
takes a list of such iterables and yields all their keys in a sequence. To do the same with the values, call values()
on each item, for which we map
a methodcaller
here (equivalent to (i.values() for i in T1)
).
Upvotes: 2
Reputation: 34086
Use List Comprehensions
:
In [148]: P1 = [list(i.keys())[0] for i in T1]
In [149]: D1 = [list(i.values())[0] for i in T1]
In [150]: P1
Out[150]: [0, 15, 19, 20, 0]
In [151]: D1
Out[151]: [0, 3, 1, 1, 0]
Upvotes: 0