gui*_*eur 1 python dictionary python-3.x
我有一本字典,我想用这个模式重命名所有键(测试编号 1 => testNumber1)
这是我的命令:
{'id': '4', 'event title': 'Coldplay World Tour', 'event start date': '29/07/2022 20:30', 'event end date': '30/07/2022 01:00', 'name of the location hosting the event (optional)': 'Stade de France', 'address of the location': '93200 Saint-Denis', 'total ticket number': '10000', 'maximum tickets per user': '6', 'sale start date': '04/05/2022', 'line up': '', 'asset url': 'https://coldplay.com/coldplay_asset.mp4'}
Run Code Online (Sandbox Code Playgroud)
在另一个 json -i 上,我做了这 2 个元素:
self.json_informations[i]['smart_contract']['collectionName'] = self.json_informations[i]['smart_contract'].pop('collection name') #on remplace collection par collectionName
Run Code Online (Sandbox Code Playgroud)
但更改所有参数会太长(而且不太灵活)。0
我也尝试了一个循环,但它不起作用:
for j in range(len(self.json_informations[0])): #my dict is in json_informations[0]
print(self.json_informations[0][j])
Run Code Online (Sandbox Code Playgroud)
但这给了我一个错误
print(self.json_informations[i][j])
KeyError: 0
Run Code Online (Sandbox Code Playgroud)
我想得到这个结果作为我的输出
{'id': '4', 'eventTitle': 'Coldplay World Tour', 'eventStartDate': '29/07/2022 20:30', 'eventEndDate': '30/07/2022 01:00', 'nameOfTheLocation': 'Stade de France', 'addressOfTheLocation': '93200 Saint-Denis', 'totalTicketNumber': '10000', 'maximumTicketsPerUser': '6', 'saleStartDate': '04/05/2022', 'lineUp': '', 'assetUrl': 'https://coldplay.com/coldplay_asset.mp4'}
Run Code Online (Sandbox Code Playgroud)
感谢您的回答!
小智 5
循环中唯一的问题是您以错误的方式循环字典。循环字典的方式如下:
mydict = {"Hi": 1, "there": 2, "fellow": 3}
for key in mydict:
print(key)
Run Code Online (Sandbox Code Playgroud)
将有一个输出:
Hi
there
fellow
Run Code Online (Sandbox Code Playgroud)
因为循环字典会将键本身作为循环变量。您试图在循环中循环整数并访问与所述整数值键对应的字典值,但如果所述键不存在,则尝试访问与键对应的项目显然会给出错误。因此,要在循环中更改字典中键的名称,您可以使用如下循环:
mydict = {"Hi": 1, "there": 2, "fellow": 3}
for key in mydict:
mydict[newkey] = mydict.pop(key)
Run Code Online (Sandbox Code Playgroud)
您会注意到这与您最初的做法类似,现在只是一个循环。