【发布时间】:2020-12-29 15:53:00
【问题描述】:
有没有办法将条目添加到 json 列表中的字典中? (P.S. 我什至不确定我是否应该这样表达这个问题)
base_server_datas = {
'users': {},
}
@commands.command()
@commands.has_any_role(*MODERATORS, *ADMINISTRATORS)
async def create(self, ctx, *args: str):
faction = load_faction()
message = " ".join(args).lower()
new_faction = message
if new_faction not in faction:
faction[new_faction] = base_server_datas.copy()
save_faction(faction)
await ctx.send(f'**{new_faction}** cult created!')
else:
await ctx.send(f"{new_faction} cult already exists")
@commands.command(case_insensitive=True)
async def join(self, ctx, *args: str):
faction = load_faction()
new_user = str(ctx.author.id)
message = " ".join(args).lower()
existing_faction = message
if existing_faction in faction:
if new_user not in faction[existing_faction]["users"]:
faction[existing_faction]["users"][new_user] = ctx.author.name
save_faction(faction)
await ctx.send(f"{ctx.author.mention} joined the **{message}** cult")
else:
await ctx.send(f"{ctx.author.mention} is already in the cult")
else:
await ctx.send("faction doesn\'t exist")
所以使用这段代码我可以创建一个派系并加入它,它看起来像这样:
{
"h": {
"users": {
"535485026905882626": "Benji",
"702646374155419648": "rosesaredumb",
"578938036960624660": "invalid-user",
"360366991149891585": "Goodra999"
}
}
}
但是我做了另一个标题“领导者”并尝试在其下添加条目,但它不起作用
看起来像这样
{
"h": [
{
"users": {}
},
{
"leaders": {}
}
]
}
这部分的代码是
base_server_datas2 = {
'leaders': {},
}
@commands.command()
async def leader(self,ctx, member: discord.Member, *args: str):
faction = load_faction()
new_user = str(member.id)
message = " ".join(args).lower()
existing_faction = message
if existing_faction in faction:
if new_user not in faction[existing_faction]["leaders"]:
faction[existing_faction]["leaders"][new_user] = member.name
save_faction(faction)
await ctx.send(f"{ctx.author.mention} joined the **{message}** cult")
else:
await ctx.send(f"{ctx.author.mention} is already in the cult")
else:
await ctx.send("faction doesn\'t exist")
添加“领导者”标题后,现在我什至无法更新“用户”字典
有什么方法可以在这两个字典中添加条目吗?
编辑:这是我想要的输出
{
"h": [
{
"users": {
"702646374155419648": "rosesaredumb",
"578938036960624660": "invalid-user"
}
},
{
"leaders": {
"57893803696076560": "josh"
}
}
]
}
【问题讨论】:
-
“在它之下”是什么意思。请在问题中显示您想要的输出,以便澄清
-
所以你的意思是如何更新字典,这本字典在列表中??
-
@Boomerang20thCentury 是的
-
@ShivamJha 我在编辑中添加了输出
标签: python json discord discord.py