首页 > 解决方案 > 在 csv 文件中创建特定行的字典

问题描述

假设我的文件有点像这样:

['720',
'717',
'"Diagnostic"',
'487',
'"{""status"": ""active""',
'""division_type"": ""Organisation""}"']

我需要选择487作为新字典中的键,并按原样选择 487 后面的单词。基本上是新字典中的字典。我已经尝试了以下代码:

for row in line:
    key = row[3]
    if key in d:
         pass
    d[key]=row[21:]
print(d)

我选择 3 是因为 487 是第三个索引,我选择 21 是因为在 csv 文件中,以下行位于第 21 行中。

我是编程新手。请帮帮我。消息中的错误是:索引超出范围

标签: pythondictionarykey

解决方案


我想说没有更多数据,以下方法或多或少是实验性的,但可能是一个很好的起点。您可以查找有问题的键(487在您的情况下)和连续的花括号:

import re
from ast import literal_eval

file = """
['720',
'717',
'"Diagnostic"',
'487',
'"{""status"": ""active""',
'""division_type"": ""Organisation""}"']"""

rx = re.compile(r'(?P<key>487)[^{}]+(?P<content>\{[^{}]+\})')

for m in rx.finditer(file):
    content = re.sub(r"""'?"+'?""", '"', m.group('content'))
    d = {m.group('key'): literal_eval(content)}
    print(d)

这产生

{'487': {'status': 'active', 'division_type': 'Organisation'}}

或者,更一般地说,作为一个函数:

def make_dict(string, key):
    rx = re.compile(r'(?P<key>' + key + ')[^{}]+(?P<content>\{[^{}]+\})')

    for m in rx.finditer(string):
        content = re.sub(r"""'?"+'?""", '"', m.group('content'))
        yield {m.group('key'): literal_eval(content)}

for d in make_dict(file, '487'):
    print(d)

一般来说,修复文件的输入格式!


推荐阅读