Xip*_*ias 13 python string recursion dictionary
.
在给定任意嵌套字典的情况下,如何将所有点更改为下划线(在dict的键中)?
我尝试的是编写两个循环,但后来我将仅限于2级嵌套字典.
这个 ...
{
"brown.muffins": 5,
"green.pear": 4,
"delicious.apples": {
"green.apples": 2
{
}
Run Code Online (Sandbox Code Playgroud)
......应该成为:
{
"brown_muffins": 5,
"green_pear": 4,
"delicious_apples": {
"green_apples": 2
{
}
Run Code Online (Sandbox Code Playgroud)
有优雅的方式吗?
the*_*eye 20
你可以编写一个递归函数,就像这样
from collections.abc import Mapping
def rec_key_replace(obj):
if isinstance(obj, Mapping):
return {key.replace('.', '_'): rec_key_replace(val) for key, val in obj.items()}
return obj
Run Code Online (Sandbox Code Playgroud)
当你用你在问题中显示的字典调用它时,你将得到一个新的字典,键中的点用_
s 替换
{'delicious_apples': {'green_apples': 2}, 'green_pear': 4, 'brown_muffins': 5}
Run Code Online (Sandbox Code Playgroud)
说明
在这里,我们只检查当前对象是否是实例,dict
如果是,则我们迭代字典,替换密钥并递归调用该函数.如果它实际上不是字典,则按原样返回.
假设.
只存在于键中,并且所有字典的内容都是原始文字,那么真正便宜的方法是使用str()
或repr()
更换,然后ast.literal_eval()
将其取回:
d ={
"brown.muffins": 5,
"green.pear": 4,
"delicious_apples": {
"green.apples": 2
} # correct brace
}
Run Code Online (Sandbox Code Playgroud)
结果:
>>> import ast
>>> ast.literal_eval(repr(d).replace('.','_'))
{'delicious_apples': {'green_apples': 2}, 'green_pear': 4, 'brown_muffins': 5}
Run Code Online (Sandbox Code Playgroud)
如果字典.
在键之外,我们可以通过使用正则表达式来'ke.y':
更换,以查找字符串,并仅替换那些位:
>>> import re
>>> ast.literal_eval(re.sub(r"'(.*?)':", lambda x: x.group(0).replace('.','_'), repr(d)))
{'delicious_apples': {'green_apples': 2}, 'green_pear': 4, 'brown_muffins': 5}
Run Code Online (Sandbox Code Playgroud)
如果您的字典非常复杂,使用'.'
值和字典类字符串等,请使用真正的递归方法.就像我在开始时说的那样,这是便宜的方式.
归档时间: |
|
查看次数: |
1889 次 |
最近记录: |