更改词典列表中的字典值


{
"__class": "Tape",
"Clips": [
{
"__class": "MotionClip",
"Id": 4280596098,
"TrackId": 4094799440,
"IsActive": 1,
"StartTime": 180,
"Duration": 48,
"ClassifierPath": "world/maps/error/timeline/moves/error_intro_walk.msm",
"GoldMove": 0,
"CoachId": 0,
"MoveType": 0,
{
"__class": "MotionClip",
"Id": 2393481294,
"TrackId": 4094799440,
"IsActive": 1,
"StartTime": 372,
"Duration": 48,
"ClassifierPath": "world/maps/error/timeline/moves/error_ve_opening.msm",
"GoldMove": 0,
"CoachId": 0,
"MoveType": 0,
...

这是 json 文件的一个片段,我想在其中更改数字的显示方式。例如,我希望 1 写成 00000001,48 写成00000048,0 写成 00000000。所以整个 json 文件中的所有数字都是按照我之前说的写的。它们可以写成字符串。 我不知道如何开始,因为我有字典列表。

假设你的数据实际上看起来像这样 -

main_dict = {
"__class": "Tape",
"Clips": [
{
"__class": "MotionClip",
"Id": 4280596098,
"TrackId": 4094799440,
"IsActive": 1,
"StartTime": 180,
"Duration": 48,
"ClassifierPath": "world/maps/error/timeline/moves/error_intro_walk.msm",
"GoldMove": 0,
"CoachId": 0,
"MoveType": 0,
},
{
"__class": "MotionClip",
"Id": 2393481294,
"TrackId": 4094799440,
"IsActive": 1,
"StartTime": 372,
"Duration": 48,
"ClassifierPath": "world/maps/error/timeline/moves/error_ve_opening.msm",
"GoldMove": 0,
"CoachId": 0,
"MoveType": 0,
}
]
}  

您可以执行以下操作 -

#Accessing a specific key in a dict, in this case Clips (list of dicts)
list_dicts = main_dict.get('Clips')  
#Function to fix/edit specific values in the list of dict based on what key they belong to
def fix_value(k,v):
if k=='Duration':
return '00000'+str(v)
#Add more elseif in between with various things you wanna handle 
else:
return v
#Iterating over each key, value in each dict in list of dicts and applying above function on the values
[{k:fix_value(k,v) for k,v in i.items()} for i in list_dicts] 

结果-

[{'__class': 'MotionClip',
'Id': 4280596098,
'TrackId': 4094799440,
'IsActive': 1,
'StartTime': 180,
'Duration': '0000048',
'ClassifierPath': 'world\/maps\/error\/timeline\/moves\/error_intro_walk.msm',
'GoldMove': 0,
'CoachId': 0,
'MoveType': 0},
{'__class': 'MotionClip',
'Id': 2393481294,
'TrackId': 4094799440,
'IsActive': 1,
'StartTime': 372,
'Duration': '0000048',
'ClassifierPath': 'world\/maps\/error\/timeline\/moves\/error_ve_opening.msm',
'GoldMove': 0,
'CoachId': 0,
'MoveType': 0}]

最新更新