简体   繁体   English

要迭代的可怕的字典列表

[英]horrible list of dicts to iterate over

I have this dictionary which is pulled from radb.net (use for network irr info) (some data sanitized)我有这本从 radb.net 中提取的字典(用于网络 irr 信息)(一些数据已清理)

{'objects': {'object': [{'type': 'route',
    'attributes': {'attribute': [{'value': '10.10.10.0/22', 'name': 'route'},
      {'name': 'descr', 'value': 'MyCorp Services, Inc.'},
      {'name': 'origin',
       'link': {'href': 'http://radb.net/api/radb/aut-num/AS11111',
        'type': 'locator'},
       'value': 'AS11111',
       'referenced-type': 'aut-num'},
      {'link': {'href': 'http://radb.net/api/radb/mntner/MAINT-RADB-AS11111',
        'type': 'locator'},
       'name': 'mnt-by',
       'value': 'MAINT-RADB-AS11111',
       'referenced-type': 'mntner'},
      {'name': 'changed', 'value': 'me@MyCorp.com 20201006'},
      {'value': 'RADB', 'name': 'source'}]},
    'primary-key': {'attribute': [{'value': '10.10.10.0/22', 'name': 'route'},
      {'name': 'origin', 'value': 'AS11111'}]},
    'source': {'id': 'radb'},
    'link': {'type': 'locator',
     'href': 'http://radb.net/api/radb/route/10.10.10.0/22AS11111'}}]},
 'service': {'name': 'search'},
 'terms-and-conditions': {'type': 'locator',
  'href': 'http://www.radb.net/register/'}}

All i really want to be able to do is print out the value '10.10.10.0/22'我真正想要做的就是打印出值'10.10.10.0/22'

I'm like 3x for lines into a loop but figure there must be a better way我喜欢 3x for线进入一个循环,但我想一定有更好的方法

code so far:到目前为止的代码:

for k,v in horrible_dict.items():
       if 'object' in v:
          for x,y in v.items():
                for k,v in [(k, v) for x in y for (k, v) in x.items()]:
                    print(v)
                    for....

To extract only that value you could do:要仅提取该值,您可以执行以下操作:

dic = #your dictionary
val = dic["objects"]["object"][0]["attributes"]["attribute"][0]["value"]

>>> val
'10.10.10.0/22'

Another approach would be with nested list comprehension if you have several values.如果您有多个值,另一种方法是使用嵌套列表理解。

from itertools import chain

result = [
      [
    [g[0]['value'] for f,g in e['attributes'].items()] 
    for e in v['object']
  ] 
    for k,v in horrible_dict.items() if 'object' in v
]

list(chain.from_iterable(result))[0]
>>>
['11.11.11.0/22']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM