[英]How to create dictionary from three different list in Python using two same Keys and different values?
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:我想要的 output 是:
{
"Labresult":[
{ 'testname': 'pizza',
'output': '12.3',
},
{ 'testname': 'dog',
'output': '356,'
},
{ 'testname': 'lion',
'output': '45.6',
}]
}
What I tried:我尝试了什么:
dict(zip(key, zip(value1,value2)))
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, eg if value1
and value2
are columns of a DataFrame.原则上,您也可以切换到基于 Pandas 的方法,例如,如果
value1
和value2
是 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:
将最初建议的方法与潜在的 pandas 方法进行比较,以处理大量数据(无 for 循环),事实证明前者要快得多:
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 (eg no nested dicts), that could allow for improvements.如果您可以选择更改所需结果的形状/数据类型(例如,没有嵌套字典),则可以进行改进。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.