-2

Suppose I have the following list of dictionaries:

list1 = [{'1': 1}, {'1': 1}, {'0': 1}, {'1': 1}, {'1': 1}, {'0': 1}]

how can I extract all the keys into a single list? The desired output should look like:

li = [1,1,0,1,1,0]

I tried to use

randlis = [list[i].keys() for i in range len(list1)]

This doesn't work since the output includes the type:

[dict_keys(['1']), dict_keys(['1']), dict_keys(['0'])]

Thanks!

ZR-
  • 809
  • 1
  • 4
  • 12
  • 1
    Don't use `list` as a variable name, you're overwriting the built-in `list` type's constructor by doing so. – ddejohn Feb 25 '21 at 23:07
  • @blorgon Ahh I see. Thanks! – ZR- Feb 25 '21 at 23:07
  • 1
    Well the problem is you've overwritten `list` to act as your dictionary. Which is very very bad practice. If you call your dictionary `dictionary`, then `list(dictionary.keys())` is the solution. – Kraigolas Feb 25 '21 at 23:07
  • Does this answer your question? [How to return dictionary keys as a list in Python?](https://stackoverflow.com/questions/16819222/how-to-return-dictionary-keys-as-a-list-in-python) – Kraigolas Feb 25 '21 at 23:10

2 Answers2

1

You can simply loop over the elements using list comprehension

[key for _dict in list for key in _dict.keys()]
#['1', '1', '0', '1', '1', '0']

Note. You should not use list or str int etc for naming variables. I have kept it the same in the example so you understand the loop better. Please change your var name to something else.

PacketLoss
  • 5,561
  • 1
  • 9
  • 27
  • 1
    Just as a heads-up, OP seems to want those keys converted to `int`, at least according to their desired outcome `li = [1,1,0,1,1,0]` I'd also recommend using descriptive iterator variables here to aid readability. – ddejohn Feb 25 '21 at 23:08
1

You can use chain from itertools:

list1 = [{'1': 1}, {'1': 1}, {'0': 1}, {'1': 1}, {'1': 1}, {'0': 1}]

from itertools import chain

randlis = list(chain(*list1))

print(randlis)
['1', '1', '0', '1', '1', '0']
Alain T.
  • 40,517
  • 4
  • 31
  • 51