0

I need to fill a JSON with touple KEY=>VALUE, where the KEY are NUMBERS from 0 to 9 and VALUE are the same NUMBERS between "(#)", how can I build the JSON???

import json
import sys

keys = []
values = []
for i in range(10):
    number = i+1
    letter= str(numerito)
    keys.insert(i,number)
    values.insert(i,"("+letter+")")

print(keys)
print(values)

#Here I need to construct the JSON
json = {}
json = ('key{}'.format(index), val) for keys, val in enumerate(value{}) #I can't understand how to make the association here

#...And y want to obtain some like that:
"""
   json = {0:"(0)",1:"(1)",2:"(2)",3:"(3)",4:"(4)",5:"(5)",6:"(6)",7:"(7)",8:"(8)",9:"(9)",}
"""

  • Does this answer your question? [How can I make a dictionary (dict) from separate lists of keys and values?](https://stackoverflow.com/questions/209840/how-can-i-make-a-dictionary-dict-from-separate-lists-of-keys-and-values) – Pranav Hosangadi Dec 20 '22 at 19:16
  • It is important to understand, this line: `json = {}` is completely pointless. Note, it looks like you are trying to build a *dictionary*. – juanpa.arrivillaga Dec 20 '22 at 19:51
  • You're defining a `dict`; whether you encode this dict as a JSON object later is irrelevant. – chepner Dec 20 '22 at 19:52

1 Answers1

0

Directly add the key-value pairs into a dictionary in the loop instead.

import json

d = {}
for i in range(10):
    d[i] = "(" + str(i) + ")"

print(d)
print(json.dumps(d)) # convert dictionary to JSON string

You can shorten the code using a dict comprehension.

d = {i : f'({i})' for i in range(10)}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80