2

I have the following data:

[{'id': ['132605', '132750', '132772', '132773', '133065', '133150', '133185', '133188', '133271', '133298']}, 
 {'number': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']}, 
 {'id': ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1']}]

What would be the best way to get a list of the keys (as if it was a dict and not an array)? Currently I'm doing:

>>> [list(i.keys())[0] for i in e.original_column_data]
['id', 'number', 'id']

But that feels a bit hackish

3 Answers3

9

What is hacky about it? It's a bit inelegant. You just need to do the following:

>>> keys = []
>>> data = [{'id': ['132605', '132750', '132772', '132773', '133065', '133150', '133185', '133188', '133271', '133298']},
...  {'number': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']},
...  {'id': ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1']}]
>>> for d in data:
...     keys.extend(d)
...
>>> keys
['id', 'number', 'id']

Or if you prefer one-liners:

>>> [k for d in data for k in d]
['id', 'number', 'id']
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • thanks for these answers, these are very helpful. Out of curiosity, why does `keys.extend(d)` only add the key and not the entire dict there? I actually had to test it to make sure it worked because it seemed so counterintuitive. (Unlike `append`) –  Dec 27 '18 at 20:20
  • 2
    `.extend` takes an iterable, and adds all the elements in the iterable to the list. `dict` objects are iterables *over their keys*. If you want an iterable of the values, use `d.values()`, if you want an iterable of the key-value pairs, use `d.items()` – juanpa.arrivillaga Dec 27 '18 at 20:21
3

first way

iteration on a dictionary gives you its keys, so a simple

>>> [key for key in dict]

gives you a list of keys and you can get what you want with

>>> [key for dict in dict_list for key in dict]

second way (only python 2)

use .key() (used in your code) but there is no need to use list() (edit: for python 2)
here's what it will look like:

>>> [dict.keys()[0] for dict in dict_list]

in your code, dictionaries have only one key so these two have the same result.
but I prefer the first one since it gives all keys of all the dictionaries

Saleh Hosseini
  • 482
  • 4
  • 11
2

This is simpler and does the same thing:

[k for d in e.original_column_data for k in d]
=> ['id', 'number', 'id']
Óscar López
  • 232,561
  • 37
  • 312
  • 386