简体   繁体   English

在Python中将相同名称的键添加到嵌套字典中

[英]Adding keys of the same name into nested dictionary in Python

I'm dealing with a little issue. 我正在处理一个小问题。 So I want to have a dictionary that looks like this json file 所以我想要一个看起来像这个json文件的字典

{"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. 问题是,如果不添加包含每个键和值的计数器,就无法在python中执行相同的操作。 For example, I want to create 10 keys for matches, that contain gameId key and platformId key, and the code looks like that 例如,我想为比赛创建10个键,其中包含gameId键和platformId键,代码看起来像这样

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 虽然我了解json文件还使用了相同形式的计数器,但是“不可见”,但我想知道是否有可能在python3中做同样的事情

Or is perhaps my reasoning wrong? 还是我的推理错了?

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 最后,如果您希望将其作为实际的json,则可以使用json标准库,并使用dumps方法创建json对象

obj = json.dumps(myDict)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM