简体   繁体   English

使用 python 从字典的嵌套列表中获取值

[英]Getting values from a nested list of dictionaries using python

nest_list_of_dicts = [[{"dictionary": 'AAPL', 'A': 1.1, 'B': 1.2, 'C': 1.3}, {"dictionary": 'NFLX', 'A': 1.4, 'B': 1.5, 'C': 1.6}],
                      [{"dictionary": 'AAPL', 'A': 2.1, 'B': 2.2, 'C': 2.3}, {"dictionary": 'NFLX', 'A': 2.4, 'B': 2.5, 'C': 2.6}],
                      [{"dictionary": 'AAPL', 'A': 3.1, 'B': 3.2, 'C': 3.3}, {"dictionary": 'NFLX', 'A': 3.4, 'B': 3.5, 'C': 3.6}]]

Hello, I'm trying to create a function which can append all of AAPL's 'A' and 'B' values in seperate lists then to find the mean average of both list's.您好,我正在尝试创建一个函数,该函数可以将 AAPL 的所有“A”和“B”值附加到单独的列表中,然后找到两个列表的平均平均值。 And the same for NFLX. NFLX 也是如此。

I'm trying to find a solution which could handle these list's expanding with more dictionaries in the future, the nested list's will always have the same amount of dictionaries and KEYS.我正在尝试找到一种解决方案,该解决方案可以处理这些列表在未来使用更多词典进行扩展,嵌套列表将始终具有相同数量的词典和密钥。

Thank you for your help in advance :)提前谢谢你的帮助 :)

I would encourage you to look into pandas.我鼓励你研究熊猫。 You can convert the list of dictionaries into a dataframe by using list comprehension and then concatenate your list of frames together.您可以使用列表理解将字典列表转换为数据帧,然后将帧列表连接在一起。 Once you have a dataframe you can groupby your key and find the mean of each column.一旦你有了一个数据框,你就可以按你的键分组并找到每列的平均值。

import pandas as pd

df = pd.concat([pd.DataFrame(l) for l in nest_list_of_dicts]).groupby('dictionary').mean()

              A    B    C
dictionary               
AAPL        2.1  2.2  2.3
NFLX        2.4  2.5  2.6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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