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>Use <em>list comprehensions</em>:</p>

<pre><code>date = [d['Date'] for d in list_of_dicts]
price = [d['price'] for d in list_of_dicts]
itemnumber = [d['itemnumber'] for d in list_of_dicts]
</code></pre>

<hr>

<p>One could also do this in a less readable one liner:</p>

<pre><code>date, price, itemnumber = zip(*[(d['Date'], d['price'], d['itemnumber']) for d in list_of_dicts])
</code></pre>

<p>Use <code>map(list, ...)</code> to turn the returned tuples into lists in the second case.</p>

python list dictionary