2

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,

3
  • 2
    What have you tried so far, and why do you think it doesn't work? Commented Mar 22, 2021 at 7:07
  • How did you end up with such a list in the first place? Commented Mar 22, 2021 at 7:07
  • Thanks for the questions. While I am not new in Python, I kept applying the same logic I use with Stata to extract the desired data, which caused me to get the error message. Commented Mar 22, 2021 at 15:00

3 Answers 3

2

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)).

Sign up to request clarification or add additional context in comments.

Comments

1

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))

2 Comments

You can replace the list comprehension with a generator expression ([]()) for even more efficiency in that zip approach.
@deceze aaargh! of course. thanks! (and there i was claiming that no additional lists are created...) i like your version too!
0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.