python - 在 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 行中。
我是编程新手。请帮帮我。消息中的错误是:索引超出范围
解决方案
我想说没有更多数据,以下方法或多或少是实验性的,但可能是一个很好的起点。您可以查找有问题的键(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)
一般来说,修复文件的输入格式!
推荐阅读
- jmeter - JMeter:如何加载在负载测试期间不可用的测试直播视频
- javascript - onClick - 从另一个文件调用函数
- jenkins - 如何在 Jenkins 上向用户发布环境仪表板
- javascript - 如何在乘法表上删除Child
- python - 如何让 TensorFlow 使用所有 CPU
- wpf - 如何从视图模型触发一些代码在视图中运行?
- javascript - 如何每秒打印 nth-child(n) 的索引?
- azure - 公司品牌不适用于 Azure 门户中的密码页面
- android - 在应用程序为后台并杀死后使用 gsm 单元位置获取 cid 和 lac
- javascript - 反应 css 优先级