python - 数据提取: Creating dictionary of dictionaries with lists in python

标签 python dictionary

我的文件中有类似于以下内容的数据:

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 列和 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)}
    

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

最佳答案

在标准库中执行此操作的最简单方法是使用现有工具,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如果这看起来很奇怪

关于python - 数据提取: Creating dictionary of dictionaries with lists in python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39918972/

相关文章:

vba - 在调用 .add() 之前添加项目的字典对象

python - 计算字符串中每个字母的频率

python - python中的数字列表到日期时间转换

python - 用于查找大于原始字符串的字符串的字符串操作算法

python - 在 PyQt 中自定义 MPL

javascript - 如何按值对关联数组进行排序并保留值?

ios - 从 Swift 中的字典中获取特定键的所有值

python - 是否有更好的函数来查找公共(public)节点列表上的边?

python - 如何将包含可迭代项作为项目的字典转换为数据框

python - 如何将此词典列表转换为表格或 csv 文件?