Dave Mcpherson
Dave Mcpherson

Reputation: 85

2D array to Dict

So my data looks like this

keys = ["Name", "Price", "Colour"]
fruits = ["Apple", "Pear", "Peach", "Banana"]
prices = [0.35, 0.40, 0.40, 0.28]
colour = ["Red", "Green", "Orange", "Yellow"]

and the result I need looks like this

expected = [
    {
        "Name": "Apple",
        "Price": 0.35,
        "colour": "Red"
    },
# ... ect 
]

I have one version of it like this

a = list(zip(fruits, prices, colour))
c = []
for value_set in a:
    b = {}
    for i, value in enumerate(value_set):
            b[keys[i]] = value
    c.append(b)

Is this the best solution or its this bad practice ?

Upvotes: 0

Views: 64

Answers (2)

user15763083
user15763083

Reputation:

Pandas-module can solve that point in just one step.

import pandas as pd

keys = ["Name", "Price", "Colour"]
fruits = ["Apple", "Pear", "Peach", "Banana"]
prices = [0.35, 0.40, 0.40, 0.28]
colour = ["Red", "Green", "Orange", "Yellow"]

df = pd.DataFrame([fruits, prices, colour], keys)
print([dict(df[i]) for i in range(3)])

Upvotes: 1

Karl Knechtel
Karl Knechtel

Reputation: 61508

We can use the same zip technique that grouped up the dict values, to line those values up with the keys. A dict can be constructed directly from key-value pairs, and a list comprehension is a more elegant way to apply the process to each group of values.

So, I would write:

groups = zip(fruits, prices, colour)
expected = [dict(zip(keys, group)) for group in groups]

Upvotes: 4

Related Questions