【问题标题】:Python 2.6 Export Dictionary multi-line to Python File in dictionary format (.py file)Python 2.6 以字典格式将字典多行导出到 Python 文件(.py 文件)
【发布时间】:2017-11-23 14:34:11
【问题描述】:

我已经探索了其他问题,但发现没有满足我需求的答案,我并不感到惊讶。

我正在吸收一个现有项目,需要对其进行一些改进。完全重写是遥不可及的事情,目前无法更改文件格式,因此我需要解决方法。

数据源是一个数据库,具有一个键/值对字段。

我正在选择数据库并导出。

问题:

我们正在创建一个新字典,然后对其进行解析。

output = []
output.append("dictionary = {" + "\n")
# dbdata is just a dictionary of data from the database containing key and value
for result in dbdata
    output.append("\"" + str(result['key']) + "\" : \"" + str(result['value']) + "\",")
output.append("}")
response = "\n".join(output)

我们现在有一个非常大的字典,将被打印出来。

当前系统的输出是这样的:

dictionary = {
    "one": "one value",
    "two": "two value",
    'three': '
    12345/54321*23:Some-Magic/Stuff
    12345/54331*23:Some-Magic/Stuff
    12345/54321*21:Some-Magic/Stuff
    12345/54321*53:Some-Magic/Stuff
    12341/54321*23:Some-Magic/Stuff
    12343/54321*23:Some-Magic/Stuff
    12347/54321*23:Some-Magic/Stuff
    12145/54321*23:Some-Magic/Stuff',
    "four":"four value", 
    'five': "['this','is','another']", 
}

所需的格式如下所示:

dictionary = {
    "one": "one value",
    "two": "two value",
    "three": """
    12345/54321*23:Some-Magic/Stuff
    12345/54331*23:Some-Magic/Stuff
    12345/54321*21:Some-Magic/Stuff
    12345/54321*53:Some-Magic/Stuff
    12341/54321*23:Some-Magic/Stuff
    12343/54321*23:Some-Magic/Stuff
    12347/54321*23:Some-Magic/Stuff
    12145/54321*23:Some-Magic/Stuff""",
    "four":"four value", 
    "five":['this','is','another'],
}

注意:你会看到在现有的,它是:

  • 不应该引用键“五”
  • 不应三重引用“三” - 一个多行值。

关于为什么这不是重复的注释:

  • 无法将格式更改为更合理/健全的格式,即 CSV、JSON、YML - 所有其他线程(非常正确)都建议更改它。
  • 为了便于阅读,它必须保持多行格式

是的,我意识到这很荒谬,因为它不是一种人类可读的格式。

抱歉,文字太长了,这是一个难以解释的问题 - 我意识到这整件事的设计很糟糕。

感谢任何可以提供帮助的人。

【问题讨论】:

  • 我仍然不清楚您在使用什么。 export = ["dictionary = {",(above_data_here_from_database),'}'] 应该是什么? above_data_here_from_database 是什么?一个元组?包含字符串?能举个例子吗?
  • 你问的不是很清楚,但是[Python]: pprint.pprint 可以帮忙吗?如果是,请使用pprint.pformat 将其存储在字符串中,然后将字符串写入某个文件。无论如何,请向我们展示它的示例,以及您希望它如何。
  • @juanpa.arrivillaga - 不,正在创建一个数组,我们正在嵌入字典“dictionary = {”的第一个组件,然后将数据作为键:值插入。很抱歉造成混乱。
  • “数组”是什么意思?同样,您能否给出一个您正在使用的数据的具体示例?我完全不清楚......
  • @CristiFati - 我试过漂亮的打印,它不能解决问题。也许我使用不正确。我将编辑帖子

标签: python python-2.7 dictionary


【解决方案1】:

我想通了 - 至少对于我自己的用例而言。

为了清楚起见,我正在执行以下操作:

  • 检查是否为 JSON
  • 检查是否有 Python 列表
  • 如果是字符串,请引用它
  • 如果是多行,请使用三引号

这是解决我的问题的代码 - 当然,如果有更好的解决方法的建议,我很想知道。

import ast
import json


dictionary = {
    "one": "one value",
    "two": "two value",
    "three": """
    12345/54321*23:Some-Magic/Stuff
    12345/54331*23:Some-Magic/Stuff
    12345/54321*21:Some-Magic/Stuff
    12345/54321*53:Some-Magic/Stuff
    12341/54321*23:Some-Magic/Stuff
    12343/54321*23:Some-Magic/Stuff
    12347/54321*23:Some-Magic/Stuff
    12145/54321*23:Some-Magic/Stuff""",
    "four": "four value",
    "five": "['this','is','another']",
}


def export_python_formatting(input):
    output = "config = { \n"
    evalVal = ""

    for key, value in input.items():
        isJSON = False
        output += "    "
        key = str(key)


        # See if the value is correct JSON

        try:
            z = json.loads(value)
            # Valid JSON - This might be a possible datatype in my use case.
            output += '"' + key + '"' + ":" + "'''" + value + "'''"
            evalVal = value
            isJSON = True
        except:
            # Invalid JSON - So let's use literal_eval to see if it contains a list
            try:
                evalVal = ast.literal_eval(value)
            except SyntaxError:
                evalVal = value
            except ValueError:
                print("There was a value error with " + key)

        varType = type(evalVal)

        # print(varType)
        if varType is str:
            if "\n" in value:
                output += '"' + key + '"' + ":" + "'''" + value + "'''"
            else:
                if isJSON is False:
                    output += '"' + key + '"' + ":" + '"' + value + '"'
        else:
            output += '"' + key + '"' + ":" + str(value)

        output += ",\n"

    output  += "}"
    return output


x = export_python_formatting(dictionary)
print(x)

感谢所有提供帮助的人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-23
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    • 1970-01-01
    • 2018-01-11
    相关资源
    最近更新 更多