How to create three separate lists of values from a Python list of dictionaries where each dictionary has three keys
<p>I am new to Python. My question might come across as simple to experienced developers and coders but I haven't been able to find out an answer to this. </p>

<p>I am retrieving some data through a database query. I have succeeded in organising each row returned by query as a dictionary having three keys and a corresponding value to each key. Essentially, I have organised all rows of data returned by the query into a list of dictionaries.</p>

<p>The list of dictionaries looks somewhat like this:</p>

<pre><code>[
    {'Date': date1, 'price': price1, 'itemnumber': number1},
    {'Date': date2, 'price': price2, 'itemnumber': number2},
    ...
]
</code></pre>

<p>How can I convert this list of dictionaries into three separate lists corresponding to each key i.e. Date, Price and itemnumber?</p>

<p>Thank you for your help. </p>

<p>You could combine a listcomp and a dictcomp:</p>

<pre><code>In [95]: ds
Out[95]: 
[{'Date': 'date1', 'itemnumber': 'number1', 'price': 'price1'},
 {'Date': 'date2', 'itemnumber': 'number2', 'price': 'price2'}]

In [96]: {key: [subdict[key] for subdict in ds] for key in ds[0]}
Out[96]: 
{'Date': ['date1', 'date2'],
 'itemnumber': ['number1', 'number2'],
 'price': ['price1', 'price2']}
</code></pre>

<p>Note that we have three separate lists, they're just more conveniently stored as values in a dictionary.  This way, if we decide that we want to add an additional trait (say, "purchaser"), we don't need to change any of the logic.</p>

python list dictionary