Skip to content
Advertisement

Pythonic way to extract keys and multiple values from a list of dicts

I have some code which works, data is read in from a text file as a list of dicts, the code takes the keys and values from each dict in for loops. While it works I am sure there is a better way to do it than mine below:

Code

data_list = [{'Clk': '190', '50%': '5.3149999999999995', '100%': '4.715'}, 
{'Clk': '195', '50%': '5.295', '100%': '4.765'}, 
{'Clk': '200', '50%': '5.395', '100%': '4.9'}, 
{'Clk': '205', '50%': '5.55', '100%': '4.970000000000001'},
 {'Clk': '210', '50%': '5.68', '100%': '5.005'}, 
 {'Clk': '215', '50%': '5.725', '100%': '5.08'}, 
 {'Clk': '220', '50%': '5.85', '100%': '5.215'}, 
 {'Clk': '225', '50%': '6.03', '100%': '5.35'}, 
 {'Clk': '230', '50%': '6.140000000000001', '100%': '5.395'},
  {'Clk': '235', '50%': '6.074999999999999', '100%': '5.37'}, 
  {'Clk': '240', '50%': '6.02', '100%': '5.345'}, 
  {'Clk': '245', '50%': '6.025', '100%': '5.49'}, 
{'Clk': '290', '50%': '5.67', '100%': '5.37'}]

#print(data_list)
#print('n'*3)
Clk = []
av_50 = []
av_100 = []
for dicty in data_list:
    for k,v in dicty.items():
        #print("  ", v)
        if k == "Clk":
            Clk.append(dicty["Clk"])
        if k == "50%":
            av_50.append(dicty["50%"])
        if k == "100%":
            av_100.append(dicty["100%"])
print('n'*3)
print(Clk)
print('n')
print(av_50)
print('n')
print(av_100)

Outputs

['190', '195', '200', '205', '210', '215', '220', '225', '230', '235', '240', '245', '290']


['5.3149999999999995', '5.295', '5.395', '5.55', '5.68', '5.725', '5.85', '6.03', '6.140000000000001', '6.074999999999999', '6.02', '6.025', '5.67']


['4.715', '4.765', '4.9', '4.970000000000001', '5.005', '5.08', '5.215', '5.35', '5.395', '5.37', '5.345', '5.49', '5.37']

Advertisement

Answer

I would recommand using pandas.DataFrame very convenient way to

import pandas as pd

data_list = [{'Clk': '190', '50%': '5.3149999999999995', '100%': '4.715'}, 
{'Clk': '195', '50%': '5.295', '100%': '4.765'}, 
{'Clk': '200', '50%': '5.395', '100%': '4.9'}, 
{'Clk': '205', '50%': '5.55', '100%': '4.970000000000001'},
 {'Clk': '210', '50%': '5.68', '100%': '5.005'}, 
 {'Clk': '215', '50%': '5.725', '100%': '5.08'}, 
 {'Clk': '220', '50%': '5.85', '100%': '5.215'}, 
 {'Clk': '225', '50%': '6.03', '100%': '5.35'}, 
 {'Clk': '230', '50%': '6.140000000000001', '100%': '5.395'},
  {'Clk': '235', '50%': '6.074999999999999', '100%': '5.37'}, 
  {'Clk': '240', '50%': '6.02', '100%': '5.345'}, 
  {'Clk': '245', '50%': '6.025', '100%': '5.49'}, 
{'Clk': '290', '50%': '5.67', '100%': '5.37'}]

my_data=pd.DataFrame(data_list)


clk = my_data['Clk'].tolist()
clk

Regards

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement