删除保存值的python dict中的一个级别

Sco*_*oby 2 python json dictionary python-2.7 python-3.x

我有以下python字典:

'load_balancers': {'App': {'DJMatcher': {'security_group': 'sg-618d1c05', 'service_name': 'djmatcher/svc', 'certificateId': 'net', 'health_check_path': '/djmatcherstatus/ma.html', 'DNS': {'fde': {'record_name': 'platform-enrichment-djmatcher', 'ttl': 60}}}}}
Run Code Online (Sandbox Code Playgroud)

现在它基本上代表以下YAML:

 LoadBalancers:
    App:
        DJMatcher:
            certificateId: 'net'
            health_check_path: /djmatcherstatus/ma.html
            security_group: *svc_sg1
            service_name: *sn
            DNS:
                fde:
                    record_name: platform-enrichment-djmatcher
                    ttl: 60
Run Code Online (Sandbox Code Playgroud)

我想删除第二级密钥 - "App"并保持其余部分原样,这意味着生成的python字典应该成为我删除密钥App的地方,但现在该值变为其父密钥"load_balancers"的值:

'load_balancers': {'DJMatcher': {'security_group': 'sg-618d1c05', 'service_name': 'djmatcher/svc', 'certificateId': 'net', 'health_check_path': '/djmatcherstatus/ma.html', 'DNS': {'fde': {'record_name': 'platform-enrichment-djmatcher', 'ttl': 60}}}}
Run Code Online (Sandbox Code Playgroud)

有什么好办法实现这个目标吗?

kek*_*coh 7

derp['load_balancers'] = derp['load_balancers']['App']
Run Code Online (Sandbox Code Playgroud)

  • 可以,但是有一个缺点。如果您只对 v 字典的一个键感兴趣,但它有多个项目,您会得到随机结果,因为字典没有排序!您的方法基本上是“将 v 字典的“load_balancers”中的第一个随机项的第一个值放入文档字典中” (2认同)

use*_*786 5

尽管该问题并没有要求一种通用的解决方案,但我认为为将来的搜索者的利益而制定一个解决方案可能是值得的(以防OP将来遇到更复杂的情况)。

def removeLevel(d, level):
    if type(d) != type({}):
        return d

    if level == 0:
        removed = {}
        for k, v in d.iteritems():
            if type(v) != type({}):
                continue
            for kk, vv in v.iteritems():
                removed[kk] = vv
        return removed

    removed = {}
    for k, v in d.iteritems():
        removed[k] = removeLevel(v, level-1)
    return removed
Run Code Online (Sandbox Code Playgroud)

此过程将递归运行,直到达到要删除的正确级别,然后向上复制所有子项键。

例如:

>>> d = {'load_balancers': {'App': {'DJMatcher': {'security_group': 'sg-618d1c05', 'service_name': 'djmatcher/svc', 'certificateId': 'net', 'health_check_path': '/djmatcherstatus/ma.html', 'DNS': {'fde': {'record_name': 'platform-enrichment-djmatcher', 'ttl': 60}}}}}}
>>> removeLevel(d, 1)

{'load_balancers': {'DJMatcher': {'security_group': 'sg-618d1c05', 'service_name': 'djmatcher/svc', 'certificateId': 'net', 'DNS': {'fde': {'record_name': 'platform-enrichment-djmatcher', 'ttl': 60}}, 'health_check_path': '/djmatcherstatus/ma.html'}}}

>>> d2 = {'a': {'b':1, 'e':{'f':4}}, 'c':{'d':2}}
>>> removeLevel(d2, 1)

{'a': {'f': 4}, 'c': {}}

>>> removeLevel(d2, 0)

{'b': 1, 'e': {'f': 4}, 'd': 2}
Run Code Online (Sandbox Code Playgroud)