简体   繁体   中英

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:

{
 "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. 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 (eg no nested dicts), that could allow for improvements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM