我运行的函数的输出为int格式。我应该替换json文件中的号码。
"x":{..},
"y":{..},
"z":{
"zz":{
"test1": "2010-11",
"test2": "somestring",
},如何搜索test1部件并将其替换为我得到的结果的输出?
发布于 2022-10-28 21:27:39
这个问题要求的是一个5步的过程:
something.
这是这样做的代码:
import json
def some_function():
return 'hello world'
# create a dict
d = { "x":{'a':'b'},
"y":{'a':'b'},
"z":{"zz":{
"test1": "2010-11",
"test2": "somestring",
}
}
}
# call the function
x = some_function()
# change value of a specific key
d['z']['zz']['test1'] = x
# write the new json
j = json.dumps(d, indent=4)
print(j)结果如下:
{
"x": {
"a": "b"
},
"y": {
"a": "b"
},
"z": {
"zz": {
"test1": "hello world",
"test2": "somestring"
}
}
}发布于 2022-10-28 21:45:41
@D.L.的答案是正确的,因此要将函数结果赋值给字典,只需将其赋值为普通字符串或变量值。
# pretend I read data from a file, now I have a dictionary
data = {
"x": {},
"y": {},
"z": {
"zz": {
"test1": "2010-11",
"test2": "somestring",
},
},
}
# function returns the val in 'test1' by just running a string replace
# I don't know what your function does, but the
# point is the return value: newval - which is then used directly where you
# called it
def get_results(val):
newval = ''
newval = val.replace('-11', '-10')
return newval
for k,v in data.items():
if k == 'z':
for k2, v2 in data[k].items():
if 'test1' in data[k][k2].keys():
# print(data[k][k2]['test1'])
curval = data[k][k2]['test1']
newval = get_results(curval)
data[k][k2]['test1'] = newval # the return value您可以使用@D.L.中的更简洁的代码,然后分配更新的值。
发布于 2022-10-28 20:44:19
假设我理解这个问题,您应该能够在这个字典/json对象中使用键:obj‘z’‘test1 1’= "2010-10“
obj属于对象的变量名。
https://stackoverflow.com/questions/74240638
复制相似问题