为什么我在这段代码中得到“TypeError:unordered types:str()<int()?

2024-06-12 20:37:19 发布

您现在位置:Python中文网/ 问答频道 /正文

@commands.command(pass_context=True)
@checks.serverowner()
async def change(self, ctx, change):
    channel = self.bot.get_channel('432738903221469186')
    change = ctx.message.clean_content[8:]
    now = datetime.now()
    count = len(self.changes.items()) + 1
    self.changes[count] = {'date': now.strftime("%Y-%m-%d %H:%M:%S"), 'change': change}
    dataIO.save_json('data/local/changes.json', self.changes)
    await self.bot.send_message(channel, bold("\N{SPARKLE} This change to the server was just made:") + box(change))
    await self.bot.add_reaction(ctx.message, "\N{WHITE HEAVY CHECK MARK}")

给你更改.json公司名称:

^{pr2}$

以下是完整的错误:

2|cdb_laun | Traceback (most recent call last):
2|cdb_laun |   File "lib/discord/ext/commands/core.py", line 50, in wrapped
2|cdb_laun |     ret = yield from coro(*args, **kwargs)
2|cdb_laun |   File "/root/craig/cdbot/cogs/local.py", line 73, in change
2|cdb_laun |     dataIO.save_json('data/local/changes.json', self.changes)
2|cdb_laun |   File "/root/craig/cdbot/cogs/utils/dataIO.py", line 20, in save_json
2|cdb_laun |     self._save_json(tmp_file, data)
2|cdb_laun |   File "/root/craig/cdbot/cogs/utils/dataIO.py", line 50, in _save_json
2|cdb_laun |     json.dump(data, f, indent=4, sort_keys=True, separators=(",", " : "))
2|cdb_laun |   File "/usr/lib64/python3.5/json/__init__.py", line 178, in dump
2|cdb_laun |     for chunk in iterable:
2|cdb_laun |   File "/usr/lib64/python3.5/json/encoder.py", line 429, in _iterencode
2|cdb_laun |     yield from _iterencode_dict(o, _current_indent_level)
2|cdb_laun |   File "/usr/lib64/python3.5/json/encoder.py", line 352, in _iterencode_dict
2|cdb_laun |     items = sorted(dct.items(), key=lambda kv: kv[0])
2|cdb_laun | TypeError: unorderable types: str() < int()

我为这个模糊的标题和问题道歉,我只是经常处理JSON,我不理解这里的错误。我甚至不知道字符串和整数在哪里比较。在

我最初的想法是与count = len(self.changes.items()) + 1有关,但事实并非如此


Tags: inpyselfjsondatasavelineitems
2条回答

这是json.dump()中的bug,当你使用sort_keys=True并且字典中混合了int和{}键。在

您应该更改self.changes,以便它对字典键使用一致的类型。或者在从dataIO.save_json()调用sort_keys=True时不要使用sort_keys=True选项。在

对不起,我想好了。由于某些原因,在第一次运行时,它将JSON键保存为字符串。在第二次运行中,它将其保存为整数。self.changes正在打印为:

{'2': {'date': '2018-06-29 02:02:03', 'change': 'TEST'}, '1': {'date': '2018-06-29 01:07:37', 'change': 'TEST'}}

为了解决这个问题,我改变了

^{pr2}$

self.changes[str(count)] = {'date': now.strftime("%Y-%m-%d %H:%M:%S"), 'change': change}

相关问题 更多 >