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'
Grant Birchmeier
  • 17,809
  • 11
  • 63
  • 98
  • Can you please provide sample of tickets.json file? – darthbane426 Jul 08 '22 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? – tdelaney Jul 10 '22 at 01:00
  • Does this answer your question? [python generating nested dictionary key error](https://stackoverflow.com/questions/20410044/python-generating-nested-dictionary-key-error) – TheFungusAmongUs Jul 13 '22 at 04:47

1 Answers1

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}
xFueY
  • 34
  • 3
  • 1
    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. – tdelaney Jul 10 '22 at 01:01
  • 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. – xFueY Jul 10 '22 at 01:19