First : your code is fine, readable and efficient, which sounds Pythonic to me.
Note that you probably don't want a list of tuples, though. Tuples are immutable, so you wouldn't be able to append another name to names
.
With a single dict
If names
are unique, you could convert your list of dicts to a large dict:
>>> l = [{'name': 'foo', 'values': [1,2,3,4]}, {'name': 'bar', 'values': [5,6,7,8]}]
>>> data = {d['name']:d['values'] for d in l}
>>> data
{'foo': [1, 2, 3, 4], 'bar': [5, 6, 7, 8]}
You can get the desired information directly:
>>> data.keys()
dict_keys(['foo', 'bar'])
>>> data.values()
dict_values([[1, 2, 3, 4], [5, 6, 7, 8]])
If you really want a list of lists:
>>> [list(data.keys()), list(data.values())]
[['foo', 'bar'], [[1, 2, 3, 4], [5, 6, 7, 8]]]
With pandas
If you're working with a large list of dicts, you might want to consider pandas
.
You could initialize a DataFrame
directly:
>>> import pandas as pd
>>> df = pd.DataFrame([{'name': 'foo', 'values': [1,2,3,4]}, {'name': 'bar', 'values': [5,6,7,8]}])
>>> df
name values
0 foo [1, 2, 3, 4]
1 bar [5, 6, 7, 8]
If you need the names as an iterable, you can get the corresponding column:
>>> df['name']
0 foo
1 bar
Name: name, dtype: object
If you really need a list of names:
>>> list(df['name'])
['foo', 'bar']
To get the names and values together:
>>> df.values.T
array([['foo', 'bar'],
[list([1, 2, 3, 4]), list([5, 6, 7, 8])]], dtype=object)