Home > database >  How can I create a list of dicts from multiple separate lists?
How can I create a list of dicts from multiple separate lists?

Time:11-24

say I have four separate lists like so:

colors = ['red', 'blue', 'green', 'black']
widths = [10.0, 12.0, 8.0, 22.0]
lengths = [35.5, 41.0, 36.5, 36.0]
materials = ['steel', 'copper', 'iron', 'steel']

What's the best way to take this data and create a list of dicts representing objects like so:

objects = [{'color': 'red', 'width': 10.0, 'length': 35.5, 'material': 'steel'}, {'color': 'blue', 'width': 12.0, 'length': 41.0, 'material': 'copper'}, {'color': 'green', 'width': 8.0, 'length': 36.5, 'material': 'iron'}, {'color': 'black', 'width': 22.0, 'length': 36.0, 'material': 'steel'}]

I'm currently using a for loop:

for color in colors:
    obj = {}
    obj['color'] = color
    obj['width'] = widths[colors.index(color)]
    obj['length'] = lengths[colors.index(color)]
    obj['material'] = materials[colors.index(color)]
    objects.append(obj)

but this is slow for large lists so I'm wondering if there's a faster way

CodePudding user response:

This answer combines the use of a list-comprehension to easily create a list and the zip() built-in function that iterates over several iterables in parallel.

objects = [{"color": c, "width": w, "length": l, "material": m} for c, w, l, m in zip(colors, widths, lengths, materials)]

CodePudding user response:

Use the range function:

colors = ['red', 'blue', 'green', 'black']
widths = [10.0, 12.0, 8.0, 22.0]
lengths = [35.5, 41.0, 36.5, 36.0]
materials = ['steel', 'copper', 'iron', 'steel']
objects = []
for i in range(len(colors)):
    d = {}
    d['colors'] = colors[i]
    d['widths'] = widths[i]
    d['lengths'] = lengths[i]
    d['materials'] = materials[i]
    objects.append(d)

Note that all lists must have the same amount of elements as colors.

CodePudding user response:

The zip function is very useful.

objects = []
for object in zip(colors, widths, lengths, materials):
    objects.append({
        'color': object[0], 
        'width': object[1], 
        'length': object[2], 
        'material': object[3]})

CodePudding user response:

zipped = zip(colors, widths, lengths, materials)
objects = [{"color": color, "width": width, "length": length, "material": material} for color, width, length, material in zipped]
  • Related