Reputation: 758
I have three lists:
List containing keys is:
keys = ['testname', 'output']
List containing Values are:
value1 = ['pizza', 'dog', 'lion']
value2 = ['12.3', '356', '45.6']
My desired output is:
{
"Labresult":[
{ 'testname': 'pizza',
'output': '12.3',
},
{ 'testname': 'dog',
'output': '356,'
},
{ 'testname': 'lion',
'output': '45.6',
}]
}
What I tried:
dict(zip(key, zip(value1,value2)))
Upvotes: 3
Views: 404
Reputation: 6642
Good start, but you still need a loop over the values:
{"Labresult": [dict(zip(keys, pair))
for pair in zip(value1, value2)]}
Addendum:
In principle you can also switch to a Pandas based approach, e.g. if value1
and value2
are columns of a DataFrame. However, for larger amounts of data the limiting factor for your problem will always be the fact that you need to generate the nested dicts. Comparing the initially suggested approach with a potential pandas approach for larger amounts of data (no for-loop), it turns out that the former is much faster:
import numpy as np
import pandas as pd
keys = ['testname', 'output']
value1 = list(np.random.choice(['pizza', 'dog', 'lion'], 100_000))
value2 = list(map(str, np.round(np.random.random(100_000) * 1000, 1)))
%timeit {"Labresult": [dict(zip(keys, pair)) for pair in zip(value1, value2)]}
# 56 ms ± 1.8 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
df = pd.DataFrame({"testname": value1, "output": value2})
%timeit {"Labresult": df.apply(dict, axis=1).tolist()}
# 1.1 s ± 50.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
If you have the option to change the shape/data type of your desired outcome (e.g. no nested dicts), that could allow for improvements.
Upvotes: 6