Z
Z
Zagir Majidov2022-02-04 22:03:35
Python
Zagir Majidov, 2022-02-04 22:03:35

Python json why is it throwing an error?

python file:

import json
with open('test.json', 'r') as f:
  data = json.load(f)

  for items in data:
    items["1"] += [1, 2]

with open('test.json', 'w') as f:
  json.dump(data, f, indent=3)


json file:
[
   {
      "1": []
   },
   {
      "2": []
   }
]


Mistake:
items["1"] += [1, 2]
KeyError: '1'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2022-02-04
@SoreMix

And what about json? there is a dictionary . It has one key - the number 2. You are trying to get the element with the key "1":{"2": []}items["1"]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question