skip to Main Content

I have the follow JSON as an output of an enumerate function.

{'question': (0, 'Who invented the light bulb?'), 'answers': [{'answer': 'Thomas Edison', 'score': '2.0'}, {'answer': 'Nikola Tesla', 'score': '2.0'}, {'answer': 'Albert Einstein', 'score': '0.0'}], 'error': "We didn't quite get that"}

How can I remove the 0 and the enclosing bracket so it looks like this.

{'question': 'Who invented the light bulb?', 'answers': [{'answer': 'Thomas Edison', 'score': '2.0'}, {'answer': 'Nikola Tesla', 'score': '2.0'}, {'answer': 'Albert Einstein', 'score': '0.0'}], 'error': "We didn't quite get that"}

I’d appreciate any python or Regex solution. Thank you.

4

Answers


  1. Chosen as BEST ANSWER

    I just found out that I could simply use an underscore (_) for my enumerate counter to show that I won't use the variable.

    Like so:

    for _, value in enumerate(my_list):
    

    I had initially used:

    for i, value in enumerate(my_list) 
    

    but a Ruff linter in the repository I needed to push the code to kept raising issues with i not being used.


  2. if you simply want to replace the brackets and the 0 with nothing you can do:

     import re
    
     s = yourJSON
     replaced = re.sub('[(|)|0]', '', s)
     print(replaced)
    
    Login or Signup to reply.
  3. output = {
        "question": (0, "Who invented the light bulb?"),
        "answers": [
            {"answer": "Thomas Edison", "score": "2.0"},
            {"answer": "Nikola Tesla", "score": "2.0"},
            {"answer": "Albert Einstein", "score": "0.0"},
        ],
        "error": "We didn't quite get that",
    }
    question = list(output["question"])
    output["question"] = question[1]
    
    print(output)
    
    Login or Signup to reply.
  4. You don’t show your use of enumerate so I’ll answer the question as written.

    d = {
        "question": (0, "Who invented the light bulb?"),
        "answers": [
            {"answer": "Thomas Edison", "score": "2.0"},
            {"answer": "Nikola Tesla", "score": "2.0"},
            {"answer": "Albert Einstein", "score": "0.0"},
        ],
        "error": "We didn't quite get that",
    }
    
    d["question"] = d["question"][1]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search