Make pairs of labels and nested lists

Viewed 46

Given list of lists as follows:

total = [['ford', 'x', 'z', 'A', 'sedan', ['steering wheel problems', 'gearbox problems', 'broken engine']], ['fiat', 'y', 'x', 'C', 'kombi', ['steering wheel problems']], ...]

And list of fields:

labels = ['make', 'model', 'version', 'type', 'infos']

I need to create object like:

x = [[['make': ford, 'model': 'x', 'version': 'x', 'type': 'z', 'infos': ['steering wheel problems']], ['make': fiat, 'model': 'x', 'version': 'x', 'type': 'z', 'infos': ['steering wheel problems', 'gearbox problems']], ...]

How to create such thing?

2 Answers

dict() can take a list of 2-tuples as an argument, and we can construct one of those easily by using zip().

If we can add an extra label to account for the 'sedan' entry, the code becomes much more concise:

labels = ['make', 'model', 'version', 'type', 'body', 'infos']
x = [
    dict(zip(labels, entry))
    for entry in total
]
# [
#  {'make': 'ford', 'model': 'x', 'version': 'z', 'type': 'A', 'body': 'sedan', 'infos': ['steering wheel problems', 'gearbox problems', 'broken engine']}, 
#  {'make': 'fiat', 'model': 'y', 'version': 'x', 'type': 'C', 'body': 'kombi', 'infos': ['steering wheel problems']}
# ]

Otherwise, we have to manually 'edit out' that item from the list. The most succinct way is probably this:

labels = ['make', 'model', 'version', 'type', 'infos']
x = [
    dict(zip(labels, entry[:4] + entry[5:]))
    for entry in total
]
# [
#  {'make': 'ford', 'model': 'x', 'version': 'z', 'type': 'A', 'infos': ['steering wheel problems', 'gearbox problems', 'broken engine']}, 
#  {'make': 'fiat', 'model': 'y', 'version': 'x', 'type': 'C', 'infos': ['steering wheel problems']}
# ]

you can try this

total = [['ford', 'x', 'z', 'A', ['steering wheel problems', 'gearbox problems', 'broken engine']], ['fiat', 'y', 'x', 'C', ['steering wheel problems']]]
labels = ['make', 'model', 'version', 'type', 'infos']

new= [dict(zip(labels,x)) for x in total ]
print(new)

output:

[{'make': 'ford', 'model': 'x', 'version': 'z', 'type': 'A', 'infos': ['steering wheel problems', 'gearbox problems', 'broken engine']}, {'make': 'fiat', 'model': 'y', 'version': 'x', 'type': 'C', 'infos': ['steering wheel problems']}]
Related