繁体   English   中英

打印字典时如何将“:”变成“=”?

[英]How to turn “:” into “=” when printing a dictionary?

所以我使用 Python 来获取 JSON 请求,并从中制作字典。 现在我需要将其转换为 Lua 以便我可以将字典粘贴到我的 Lua 代码中; 我无法将:转换为= ,因为有很多字典。

例如,打印时 Python 字典是{"key": value}而 Lua 表只接受{"key" = value}

这是一个 hacky、脆弱的解决方案,因为 OP 说使用 JSON 库是不可能的。

目前尚不清楚 Python 字典中可能存储哪些值,但这些值很可能是字符串或其他字典。 以下尝试处理嵌套字典,并将字符串值放在引号中。 请注意,Lua 不在表构造函数中的键周围使用引号。

# Python 3 code
d = { 'one': 1, 'two': 2, 'adict': { 'x': 'a', 'y': 'b'} }

def py_dict_to_lua_table (d):
    lines = '{'
    for k, v in d.items():
        if isinstance(v, dict):
            v = py_dict_to_lua_table(v)
        elif isinstance(v, str):
            v = f'"{v}"'
        lines += f'{k} = {v},'
    lines += '}'
    return lines

lua_string = "my_lua_table = " + py_dict_to_lua_table(d)

with open('test.lua', 'w') as f:
    f.write(lua_string)

然后,从命令行:

$ python3 convert.py

然后,从 Lua:

$ lua -i test.lua 
Lua 5.3.5  Copyright (C) 1994-2018 Lua.org, PUC-Rio
> dofile "../lua/lib/utils.lua"
> table.inspect(my_lua_table)
one = 1
adict = 
        y = b
        x = a
two = 2
> my_lua_table.adict.y
b

请注意,如果 Python 字典包含不方便的值,例如 arrays,这将不起作用。 The py_dict_to_lua_table function would have to be augmented to represent Python arrays as Lua tables (or what-have-you). 如果可能的话,使用 JSON 解析库的另一个原因。

lines = []
for key, value in your_dict.items():
    lines.append(f'{"{key}"={value}} ')
with open("./dict.txt", "w"): as f:
    f.write('\n'.join(lines))

您可以使用json.JSONEncoder

from json import JSONEncoder

encoder = JSONEncoder(separators=[', ', ' = '])
dict_str = encoder.encode({'a': 1, 'b': {'c': 3, 'd': [4, 5]}})

print(dict_str)

Output:

{"a" = 1, "b" = {"c" = 3, "d" = [4, 5]}}

暂无
暂无

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

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