python - 为什么python字典占用这么多内存?

标签 python csv dictionary memory

我看到了similar question对此,但我认为我的困境在很多方面都有所不同,足以引发一个新问题。

我创建了一个函数,它打开 csv 文件并根据维度和指标列表将数据聚合到类似 json 的字典结构中。

问题是当我用它打开一个 0.97GB 的文件时,当我查看我的进程时,Python 进程正在使用大约 1.02GB 的内存。请记住,我只选择文件中的一小部分字段,并且数据是聚合的,我认为本质上它应该更小。此外,字典变量是从函数返回的唯一内容,因此这是否意味着它是函数运行后内存中唯一保留的内容?有谁知道为什么我的字典对象使用这么多内存?

**编辑 - 另外,我的理解是 csv.reader() 是一个生成器,所以我什至不会一次加载整个文件,所以它一定只是使用所有内存的字典对象?

我在 Windows 上使用 Python 2.7。

import json
import inspect
from pprint import pprint
import csv
from datetime import datetime
import sys


def jsonify_csv(fileString, dimensions, metrics, struc = {}):
    with open(fileString, 'rb') as f:
        reader=csv.reader(f)
        headings = reader.next()
        i = 0
        for line in reader:
            i+=1
            row =  {headings[i]:v for i, v in enumerate(line)}
            pointer = struc
            for dimension in dimensions:
                if dimension == 'date':
                    val = str(datetime.strptime(row[dimension], "%d/%m/%Y").date().month)
                else:
                    val = str(row[dimension])
                pointer.setdefault(val, {})
                pointer = pointer[val]
            for metric in metrics:
                pointer.setdefault(metric, 0.0)
                try:
                    pointer[metric] += float(row[metric])
                except ValueError:
                    pass
    return struc


start = datetime.today()

dims = ['brand', 'source', 'affiliate', 'country', 'store', 'salesbundle', 'product', 'ordertype', 'returncode', 'supplier', 'category']

metrics = ['sales', 'qty', 'cogs', 'carriagereclaim', 'Carriage Charged Carrier', 'carriage_est', 'mktg_est', 'mktg_cost', 'royalty', 'finance', 'scrap_cost', 'mp_cost', 'budgetsales', 'budgetcosts', 'BSTD', 'budgetaftersales', 'budgetscrap', 'budgetcarriagerecovery', 'budgetcarriagepaid', 'budgetmetapack', 'budgetmarketing', 'budgetaffiliate', 'budgetoffline', 'budgetroyalty', 'budgetfinance', 'bundle_qty', 'misc_adjustments']

jsonified = jsonify_csv('PhocasSales_2015+.csv', dims, metrics)

print 'file opened', datetime.today()-start

stop = raw_input("waiting...")

最佳答案

每次调用都将使用相同的字典。请参阅http://docs.python-guide.org/en/latest/writing/gotchas/ 。空字典 {} 在编译时创建为函数的属性。

如果您使用默认值调用该函数 28 次,您将不会获得 28 个不同的词典,它们将共享同一个词典。默认为 None,然后在函数体内测试它的值。

试试这个:

def jsonify_csv(fileString, dimensions, metrics, struc = None):
    if struc is None:
        struc = {}

    with open(fileString, 'rb') as f:
    ... # and so on

关于python - 为什么python字典占用这么多内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38616544/

相关文章:

具有多个值的 Java 映射 : container class or multiple maps?

python - 将一系列整数映射到单个整数

python - 为什么 Python 线程模块中的类公开工厂函数而不是构造函数?

# 分隔记录的 Java 正则表达式

android - 每 15 分钟将纬度和经度存储在 CSV 文件中

PHP fputcsv编码

C#:由列表索引的字典

python - 如何在 Pylons 中缓存列表/字典?

python - 从交互式控制台运行代码时无法访问数据库

python - 使用 python 字典进行排序