Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7对格式化字典键属性的递归调用_Python_Python 2.7 - Fatal编程技术网

Python 2.7对格式化字典键属性的递归调用

Python 2.7对格式化字典键属性的递归调用,python,python-2.7,Python,Python 2.7,我有一个字典数据样本 obj = { "company-name":"Name Test", "contact-name":"Test contact", "contact-phone":"1234567890", "contact-email":"test@example.com", "contact-notes":"Test Notes", "company-clients": { "client-name": "Test

我有一个字典数据样本

obj = {  
    "company-name":"Name Test",
    "contact-name":"Test contact",
    "contact-phone":"1234567890",
    "contact-email":"test@example.com",
    "contact-notes":"Test Notes",
    "company-clients": {
        "client-name": "Test Client",
        "client-address": "Test Client address",
        "client-occupation": {
            "occupation-title": "Test occupation title",
            "occupation-salary": 600000
        }
    }
} 
现在我需要它用
-
格式化所有属性,并用
-
替换它。这是理想的输出:

{  
    "company_name":"Name Test",
    "contact_name":"Test contact",
    "contact_phone":"1234567890",
    "contact_email":"test@example.com",
    "contact_notes":"Test Notes",
    "company_clients": {
        "client_name": "Test Client",
        "client_address": "Test Client address",
        "client_occupation": {
            "occupation_title": "Test occupation title",
            "occupation_salary": 600000
        }
    }
} 
到目前为止,以下是我尝试的:

def recursive_formatting(key, value):
    if not isinstance(value, dict):
        return key.replace('-', '_'), value
    else:
        for k, v in value.items():
            _k, _v = recursive_formatting(k, v)
            return _k, _v
用法

data = {}
for key, value in obj.items():
    k, v = recursive_formatting(key, value)
    data[k] = v

print data
但是,代码不进行嵌套格式化,只在格式化/更改对象属性的根级别进行嵌套格式化

这就是我得到的:

{  
    "company_name":"Name Test",
    "contact_name":"Test contact",
    "contact_phone":"1234567890",
    "contact_email":"test@example.com",
    "contact_notes":"Test Notes"
}

如果您不希望值中可能存在
-
,那么快速破解可能涉及将
obj
转储到
json
,并将
-
的所有值替换为

>>> import json
>>> obj = {  
...     "company-name":"Name Test",
...     "contact-name":"Test contact",
...     "contact-phone":"1234567890",
...     "contact-email":"test@example.com",
...     "contact-notes":"Test Notes",
...     "company-clients": {
...         "client-name": "Test Client",
...         "client-address": "Test Client address",
...         "client-occupation": {
...             "occupation-title": "Test occupation title",
...             "occupation-salary": 600000
...         }
...     }
... }

>>> new_obj = json.loads(json.dumps(obj).replace("-", "_"))
>>> new_obj
{'company_clients': {'client_address': 'Test Client address',
                     'client_name': 'Test Client',
                     'client_occupation': {'occupation_salary': 600000,
                                           'occupation_title': 'Test '
                                                               'occupation '
                                                               'title'}},
 'company_name': 'Name Test',
 'contact_email': 'test@example.com',
 'contact_name': 'Test contact',
 'contact_notes': 'Test Notes',
 'contact_phone': '1234567890'}

您可以使用递归函数,通过使用字典理解将初始字典作为参数

注意,这将返回一个新的字典,而不是对现有的字典进行修改

def recursive_format(obj):
    if isinstance(obj, dict):
        return {key.replace('-', '_'): recursive_format(value) 
                for key, value in obj.items()}
    return obj

我认为基于生成器的解决方案可能是最容易阅读的

def converter(d):
    for k, v in d.items():
        k = k.replace('-', '_')
        if isinstance(v, dict):
            yield k, dict(converter(v))
        else:
            yield k, v

from pprint import pprint
pprint(dict(converter(obj)))
印刷品

{'company_clients': {'client_address': 'Test Client address',
                     'client_name': 'Test Client',
                     'client_occupation': {'occupation_salary': 600000,
                                           'occupation_title': 'Test occupation title'}},
 'company_name': 'Name Test',
 'contact_email': 'test@example.com',
 'contact_name': 'Test contact',
 'contact_notes': 'Test Notes',
 'contact_phone': '1234567890'}

您可以使用
str.replace

def rep(d, _new = ['-', '_']):
  return {a.replace(*_new):b if not isinstance(b, dict) else rep(b) for a, b in d.items()}

print(rep(obj))
输出:

{'company_name': 'Name Test', 'contact_name': 'Test contact', 'contact_phone': '1234567890', 'contact_email': 'test@example.com', 'contact_notes': 'Test Notes', 'company_clients': {'client_name': 'Test Client', 'client_address': 'Test Client address', 'client_occupation': {'occupation_title': 'Test occupation title', 'occupation_salary': 600000}}}

您认为值中可能存在
-
字符吗?@ScottMcC-Nope,仅在
键中
为什么为
\u new
使用列表而不是元组?