0

I'm dealing with a little issue. So I want to have a dictionary that looks like this json file

{"matches":[
    {"gameId":2585563902,"platformId":"NA1"},
    {"gameId":2412534524,"platformId":"NA1"},
    {"gameId":2412534524,"platformId":"NA1"}
]}

As you can see, the key elements have the same name, with different values.

The issue is that I am unable to do the same thing in python without adding a counter, which contains each of the keys and values. For example, I want to create 10 keys for matches, that contain gameId key and platformId key, and the code looks like that

myDict = {}
myDict["matches"] = {}
for a in range (10):
    myDict["matches"][a] = {}
    myDict["matches"][a]["gameId"] = a
    myDict["matches"][a]["platformId"] = a

which returns this

{'matches': {
0: {'gameId': 0, 'accountId': 0}, 
1: {'gameId': 1, 'accountId': 1}, 
2: {'gameId': 2, 'accountId': 2}
}}

While I understand the json file also uses the same form of a counter but is "invisible", I would like to know if it is possible to do the same in python3

Or is perhaps my reasoning wrong?

Dulet
  • 3
  • 1
  • Possible duplicate of [Converting JSON String to Dictionary Not List](https://stackoverflow.com/questions/19483351/converting-json-string-to-dictionary-not-list). In particular [this answer](https://stackoverflow.com/a/48271216/499581) might provide what you are asking to do. – l'L'l Jan 12 '19 at 06:16

1 Answers1

0

Your code snippet is making a dictionary of dictionaries while instead I assume you want it to make a list of dictionaries. You can do something like this instead.

myDict = {}
myDict["matches"] = []
for a in range (10):
    innerDict = {"gameId":a, "platformId":a}
    myDict["matches"].append(innerDict)

And in the end if you want this as an actual json you use the json standard library and use the dumps method to make a json object

obj = json.dumps(myDict)
yeshks
  • 101
  • 6