0
with open("data/tickets.json", "r") as f:
    data = json.load(f)

data[str(ticket.id)]["author"] = ctx.author.id

with open("data/tickets.json", "w") as f:
    json.dump(data, f, indent=4)

I want to create in a json file, the ticket id and the author of this ticket. But i want it looks so:

{
    "random_channel_id" {
        "author": "random_user_id"
    }
}

But its give me this error:

Traceback (most recent call last):
  File "C:\Users\omalo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 383, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\omalo\OneDrive\Desktop\Home Bot\cogs\Ticket.py", line 46, in TicketCreation
    data[str(ticket.id)]["author"] = ctx.author.id
KeyError: '995020823683412029'
3
  • Can you please provide sample of tickets.json file? Commented Jul 8, 2022 at 17:49
  • data[str(ticket.id)]["author"] = ctx.author.id would work if you have an existing str(ticket.id) and you want to add (or change) "author" in it. The error tells you it doesn't exist in this case. But, is this always the case? Are you trying to update an existing entry? Commented Jul 10, 2022 at 1:00
  • Does this answer your question? python generating nested dictionary key error Commented Jul 13, 2022 at 4:47

1 Answer 1

1

From my testing and knowledge, the issue is that you are trying to create the author key in a nested dictionary that does not exist, which is not possible.

>>> x = {}
>>> x[123]['author'] = 456
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 123

So if you create the key 123 first (or in your case, the ticket id), but with an empty dictionary, and then the author key in the nested dictionary, it will work:

data[str(ticket.id)] = {}
data[str(ticket.id)]["author"] = ctx.author.id

Alternatively; you could also do it at once:

data[str(ticket.id)] = {"author" : ctx.author.id}
Sign up to request clarification or add additional context in comments.

2 Comments

Great answer but it assumes that OP wants to create a new data item as opposed to updating an existing one. I think we will need some clarification from OP.
I think that's what OP meant with "I want to create in a json file, the ticket id and the author of this ticket.", but you might be right. Guess we'll wait on OP and see.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.