每当键为'current_values'时,我希望用相同值的整数替换(格式化为字符串的)值。
d = {'id': '10', 'datastreams': [{'current_value': '5'}, {'current_value': '4'}]}
期望输出:
d = {'id': '10', 'datastreams': [{'current_value': 5}, {'current_value': 4}]}
每当键为'current_values'时,我希望用相同值的整数替换(格式化为字符串的)值。
d = {'id': '10', 'datastreams': [{'current_value': '5'}, {'current_value': '4'}]}
期望输出:
d = {'id': '10', 'datastreams': [{'current_value': 5}, {'current_value': 4}]}
def dict_replace_value(d: dict, old: str, new: str) -> dict:
x = {}
for k, v in d.items():
if isinstance(v, dict):
v = dict_replace_value(v, old, new)
elif isinstance(v, list):
v = list_replace_value(v, old, new)
elif isinstance(v, str):
v = v.replace(old, new)
x[k] = v
return x
def list_replace_value(l: list, old: str, new: str) -> list:
x = []
for e in l:
if isinstance(e, list):
e = list_replace_value(e, old, new)
elif isinstance(e, dict):
e = dict_replace_value(e, old, new)
elif isinstance(e, str):
e = e.replace(old, new)
x.append(e)
return x
# See input and output below
output = dict_replace_value(input, 'string', 'something')
输入:
input = {
'key1': 'a string',
'key2': 'another string',
'key3': [
'a string',
'another string',
[1, 2, 3],
{
'key1': 'a string',
'key2': 'another string'
}
],
'key4': {
'key1': 'a string',
'key2': 'another string',
'key3': [
'a string',
'another string',
500,
1000
]
},
'key5': {
'key1': [
{
'key1': 'a string'
}
]
}
}
输出:
print(output)
{
"key1":"a something",
"key2":"another something",
"key3":[
"a something",
"another something",
[
1,
2,
3
],
{
"key1":"a something",
"key2":"another something"
}
],
"key4":{
"key1":"a something",
"key2":"another something",
"key3":[
"a something",
"another something",
500,
1000
]
},
"key5":{
"key1":[
{
"key1":"a something"
}
]
}
}
d = {'id': '10', 'datastreams': [{'current_value': '5'}, {'current_value': '4'}]}
for elem in d['datastreams']: # for each elem in the list datastreams
for k,v in elem.items(): # for key,val in the elem of the list
if 'current_value' in k: # if current_value is in the key
elem[k] = int(v) # Cast it to int
print(d)
输出:
{'id': '10', 'datastreams': [{'current_value': 5}, {'current_value': 4}]}
最初的回答:
def f(d):
for k,v in d.items():
if k == 'current_value':
d[k] = int(v)
elif type(v) is list:
for item in v:
if type(item) is dict:
f(item)
>>> d = {'id': '10', 'datastreams': [{'current_value': '5'}, {'current_value': '4'}]}
>>> f(d)
>>> d
{'id': '10', 'datastreams': [{'current_value': 5}, {'current_value': 4}]}
d['datastreams'] = [{'current_value': int(ds['current_value'])} if ('current_value' in ds) else ds for ds in d['datastreams']]
import ast
d = {'id': '10', 'datastreams': [{'current_value': '5'}, {'current_value': '4'}]}
for i in d['datastreams']:
for k,v in i.items():
if 'current_value' in k and isinstance(ast.literal_eval(v),int):
i[k] = int(v)
#Output:
print(d)
{'id': '10', 'datastreams': [{'current_value': 5}, {'current_value': 4}]}
for value in d.values():
for element in value:
if 'current_value' in element:
element['current_value'] = int(element['current_value'])
将alec_djinn的解决方案稍微扩展一下,以处理嵌套字典:
def f(d):
for k,v in d.items():
if k == 'current_value':
d[k] = int(v)
elif type(v) is list:
for item in v:
if type(item) is dict:
f(item)
if type(v) is dict:
f(v)
def replace_in_iterable(src: Union[dict, list], old: Union[str, Callable], new: str = None):
"""
Replaces every instance of old with new in a list/dict
If old is a callable function, it will replace every instance of old win callable(old)
"""
def _replace_in_iterable(_src):
if isinstance(_src, dict) or isinstance(_src, list):
_src = replace_in_iterable(_src, old, new)
elif isinstance(old, Callable):
_src = old(_src)
elif isinstance(_src, str):
_src = _src.replace(old, new)
return _src
if isinstance(src, dict):
result = {}
for key, value in src.items():
result[key] = _replace_in_iterable(value)
elif isinstance(src, list):
result = []
for entry in src:
result.append(_replace_in_iterable(entry))
else:
result = _replace_in_iterable(src)
return result
pip install ofunctions.misc
from ofunctions.misc import replace_in_iterable
def test(string):
return f"-{string}-"
output = replace_in_iterable(input, test)
输入
input = {
'key1': 'a string',
'key2': 'another string',
'key3': [
'a string',
'another string',
[1, 2, 3],
{
'key1': 'a string',
'key2': 'another string'
}
],
'key4': {
'key1': 'a string',
'key2': 'another string',
'key3': [
'a string',
'another string',
500,
1000
]
},
'key5': {
'key1': [
{
'key1': 'a string'
}
]
}
}
输出
input = {
'key1': '-a string-',
'key2': '-another string-',
'key3': [
'-a string-',
'-another string-',
['-1-', '-2-', '-3-'],
{
'key1': '-a string-',
'key2': '-another string-'
}
],
'key4': {
'key1': '-a string-',
'key2': '-another string-',
'key3': [
'-a string-',
'-another string-',
'-500-',
'-1000-'
]
},
'key5': {
'key1': [
{
'key1': '-a string-'
}
]
}
}
output = replace_in_iterable(input, "string", "something)
仍然有效。