循环遍历Python中的嵌套字典/列表并保存键值对。

huangapple go评论56阅读模式
英文:

loop through nested dictionary/list in Python and save key-value pairs

问题

I can help you with the translations:

Original Content:

I'd like to loop through this nested dict/list and return all occurrences of input key-value pairs. The length and the depth of each level may vary.

For example I'd like to have all the `{'dd': 22}`.

Here's my attempt:

d = {'a': 'foo',
    'b': [{'cc': 11},
         {'dd': 22}],
    'c': [{'dd': 22},
         {'ff': 33}]}

def navigate_html(d, key='', value='', ll=[]):
    if isinstance(d, list):
        for v in d:
            yield from navigate_html(v, key, value, ll)
    if isinstance(d, dict):
        for k, v in d.items():
            if k == key and v == value:
                ll.append({k: v})
            else:
                yield from navigate_html(v, key, value, ll)
    return ll

for i in navigate_html(d, 'dd', 22):
    print('---', i)

Desired Output:
[{'dd': 22}, {'dd': 22}]

Edited Content:

d1={'doctype': ['html'],
 'html': [{'@lang': 'en-EN',
   '#text': "ttt",
   'head': [{'#text': 'abc',
     'meta': [{'@charset': 'utf-8', '#text': ''},
      {'@name': 'viewport',
       '@content': 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no',
       '#text': ''},
      {'@name': 'description',
       '@content': 'cccc',
       '#text': '',
       'meta': [{'@name': 'keywords',
         '@content': 'cccc',
         '#text': ''}]
      }]
            }]}
   }

Expected Output:
[{'@content': 'cccc'}, {'@content': 'cccc'}]

英文:

I'd like to loop through this nested dict/list and return all occurrences of input key-value pairs. The length and the depth of each level may vary.

For example I'd like to have all the {'dd': 22}.

Here's my attempt:

d = {'a': 'foo',
    'b': [{'cc': 11},
         {'dd': 22}],
    'c': [{'dd': 22},
         {'ff': 33}]}

def navigate_html(d, key='', value='', ll=[]):
    if isinstance(d, list):
        for v in d:
            yield from navigate_html(v, key, value, ll)
    if isinstance(d, dict):
        for k, v in d.items():
            if k == key and v == value:
                ll.append({k: v})
            else:
                yield from navigate_html(v, key, value, ll)
    return ll

for i in navigate_html(d, 'dd', 22):
    print('---', i)

desired output
[{'dd': 22}, {'dd': 22}]

EDIT
better, try to retrieve '@content': 'cccc'

d1={'doctype': ['html'],
 'html': [{'@lang': 'en-EN',
   '#text': "ttt",
   'head': [{'#text': 'abc',
     'meta': [{'@charset': 'utf-8', '#text': ''},
      {'@name': 'viewport',
       '@content': 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no',
       '#text': ''},
      {'@name': 'description',
       '@content': 'cccc',
       '#text': '',
       'meta': [{'@name': 'keywords',
         '@content': 'cccc',
         '#text': ''}]
      }]
            }]
          }]
   }

expected output:
[{'@content': 'cccc'}, {'@content': 'cccc'}]

答案1

得分: 2

def navigate_html(nested: dict, key, value):
    for k, v in nested.items():
        if k == key and v == value:
            yield {k: v}
        elif isinstance(v, list):
            for d in v:
                if isinstance(d, dict):
                    yield from navigate_html(d, key, value)
英文:
def navigate_html(nested: dict, key, value):
    for k, v in nested.items():
        if k == key and v == value:
            yield {k: v}
        elif isinstance(v, list):
            for d in v:
                if isinstance(d, dict):
                    yield from navigate_html(d, key, value)

>>> list(navigate_html(d, 'dd', 22))
# => [{'dd': 22}, {'dd': 22}]

>>> list(navigate_html(d1, '@content', 'cccc'))
# => [{'@content': 'cccc'}, {'@content': 'cccc'}]

huangapple
  • 本文由 发表于 2023年6月1日 00:28:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76375593.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定