Alex Alex - 1 year ago 87
Python Question

Inquiry on dictionary comprehension

The following code is a bit from a bigger piece. lines is a 2D list and keyss is a 1D list. All element in lines is the same length as keyss.

datadict = []
for element in lines:
for index in range(len(element)):
datadict.append({keyss[index]: element[index]})

I was wondering if there was a way of writing this using dictionary comprehension? This is more of a curious question as the shown code works just fine for what I'm doing. I've been trying and couldn't find a way too. If you can could go over the syntax of how it would look a bit as well, Thanks!


Reading through the responses, I realized it wasn't really working. I'm trying to do a list comprehension where every element is a dictionary comprehension. I'm not entirely sure if that is possible or not. I want to make a list of dictionaries where I take every element in keyss and match index for index in a element in lines which is a list, if that makes sense.

EDIT #2:
I found
data_list = [{keyss[i]:row[i] for i in range(len(keyss))} for row in lines]
to work.

Answer Source

A dictionary comprehension creates a dictionary. You want a list comprehension:

datalist = [{keyss[index]:element[index]}) for element in lines
            for index in range(len(element))]

You can find the documentation on the syntax here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download