【问题标题】:Data extraction: Creating dictionary of dictionaries with lists in python数据提取:在 python 中使用列表创建字典字典
【发布时间】:2017-02-16 13:19:25
【问题描述】:

我在一个文件中有类似以下的数据:

Name, Age, Sex, School, height, weight, id

Joe, 10, M, StThomas, 120, 20, 111

Jim, 9, M, StThomas, 126, 22, 123

Jack, 8, M, StFrancis, 110, 15, 145

Abel, 10, F, StFrancis, 128, 23, 166

实际数据可能是 100 列和一百万行。

我想要做的是按照以下模式创建一个字典:

school_data = {'StThomas': {'weight':[20,22], 'height': [120,126]},
               'StFrancis': {'weight':[15,23], 'height': [110,128]} }

我尝试过的事情:

  1. 试用 1:(在计算方面非常昂贵)

    school_names  = []
    for lines in read_data[1:]:
        data = lines.split('\t')
        school_names.append(data[3])
    
    school_names = set(school_names)
    
    for lines in read_data[1:]:
        for school in schools:
            if school in lines:
                print lines
    
  2. 试验 2:

    for lines in read_data[1:]:
        data = lines.split('\t')
        school_name = data[3]
        height = data[4]
        weight = data[5]
        id = data [6]
        x[id] = {school_name: (weight, height)}
    

以上两种是我尝试过但没有更接近解决方案的方法。

【问题讨论】:

  • 其他列是什么?它们是否与计算相关,或者您是否希望像处理体重/身高(按学校分组值)一样处理这些额外的列?

标签: python dictionary


【解决方案1】:

在标准库中执行此操作的最简单方法是使用现有工具 csv.DictReadercollections.defaultdict

from collections import defaultdict
from csv import DictReader

data = defaultdict(lambda: defaultdict(list))  # *

with open(datafile) as file_:
    for row in DictReader(file_):
        data[row[' School'].strip()]['height'].append(int(row[' height']))
        data[row[' School'].strip()]['weight'].append(int(row[' weight']))

请注意,例如' School'.strip() 是必需的,因为输入文件的标题行中有空格。结果:

>>> data
defaultdict(<function <lambda> at 0x10261c0c8>, {'StFrancis': defaultdict(<type 'list'>, {'weight': [15, 23], 'height': [110, 128]}), 'StThomas': defaultdict(<type 'list'>, {'weight': [20, 22], 'height': [120, 126]})})
>>> data['StThomas']['height']
[120, 126]

或者,如果您打算进行进一步分析,请查看pandas 及其DataFrame 数据结构。

* 如果这看起来很奇怪,请参阅Python defaultdict and lambda

【讨论】:

  • 效果很好!谢谢
猜你喜欢
  • 2017-05-05
  • 2016-01-08
  • 2022-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-07
  • 1970-01-01
  • 2019-08-07
相关资源
最近更新 更多