【问题标题】:Creating a dictionary of a particular row in a csv file在 csv 文件中创建特定行的字典
【发布时间】:2019-02-20 18:00:35
【问题描述】:

假设我的文件是这样的:

['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 行中。

我是编程新手。请帮帮我。 消息中的错误是:index is out of range

【问题讨论】:

  • 我无法共享数据。不,它不是 JSON 字符串。

标签: python dictionary key


【解决方案1】:

我想说,如果没有进一步的数据,以下方法或多或少是实验性的,但可能是一个很好的起点。您可以查找有问题的密钥(在您的情况下为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)

一般情况下,修复文件的输入格式!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-03
    • 2011-10-08
    • 2012-12-15
    • 2012-01-02
    • 2016-11-22
    相关资源
    最近更新 更多