繁体   English   中英

将.gz文件中的行附加到字典python

[英]Append lines from .gz file to dictionary python

我正在尝试从.gz文件返回字典

这是我的文件内容的外观:

[go]{"id": "1", "hello": 12345}
[gsdhgo]{"id": "2", "hello": 123456}
[hff]{"id": "3", "hello": 1234567}
[fska]{"id": "4", "hello": 12345678}

我的代码:

import gzip
import re

def removeSquareBrackets():
    contents = {}
    content = []
    with gzip.open('test_gzip_file.txt.gz') as f_in:
        for line in f_in:
            line = re.sub(r'.*{','{',line)
            line = line[:-1]
            content.append(line)
            contents[content] = []
    return contents


def printFun():
    print removeSquareBrackets()

printFun();

预期输出为以下内容的字典:

{"id": "1", "hello": 12345}
{"id": "2", "hello": 123456}
{"id": "3", "hello": 1234567}
{"id": "4", "hello": 12345678}

谁能纠正我或指导我正确的方向?

我收到TypeError: unhashable type: 'list'

在脚本的第12行上,您尝试将列表内容用作字典内容中的键。 但是列表不是可散列的类型。

如果只需要输出,则指定为什么不只是:

import gzip import json content = list() with gzip.open('tmp.file.gz') as f_in: for line in f_in: content.append(json.loads(line[line.find(']')+1:].strip()))

也许您还有其他原因使字典和正则表达式的使用复杂化?

暂无
暂无

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

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