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

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

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

问题

I can help you with the translations:

Original Content:

  1. 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.
  2. For example I'd like to have all the `{'dd': 22}`.
  3. Here's my attempt:
  4. d = {'a': 'foo',
  5. 'b': [{'cc': 11},
  6. {'dd': 22}],
  7. 'c': [{'dd': 22},
  8. {'ff': 33}]}
  9. def navigate_html(d, key='', value='', ll=[]):
  10. if isinstance(d, list):
  11. for v in d:
  12. yield from navigate_html(v, key, value, ll)
  13. if isinstance(d, dict):
  14. for k, v in d.items():
  15. if k == key and v == value:
  16. ll.append({k: v})
  17. else:
  18. yield from navigate_html(v, key, value, ll)
  19. return ll
  20. for i in navigate_html(d, 'dd', 22):
  21. print('---', i)

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

Edited Content:

  1. d1={'doctype': ['html'],
  2. 'html': [{'@lang': 'en-EN',
  3. '#text': "ttt",
  4. 'head': [{'#text': 'abc',
  5. 'meta': [{'@charset': 'utf-8', '#text': ''},
  6. {'@name': 'viewport',
  7. '@content': 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no',
  8. '#text': ''},
  9. {'@name': 'description',
  10. '@content': 'cccc',
  11. '#text': '',
  12. 'meta': [{'@name': 'keywords',
  13. '@content': 'cccc',
  14. '#text': ''}]
  15. }]
  16. }]}
  17. }

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:

  1. d = {'a': 'foo',
  2. 'b': [{'cc': 11},
  3. {'dd': 22}],
  4. 'c': [{'dd': 22},
  5. {'ff': 33}]}
  6. def navigate_html(d, key='', value='', ll=[]):
  7. if isinstance(d, list):
  8. for v in d:
  9. yield from navigate_html(v, key, value, ll)
  10. if isinstance(d, dict):
  11. for k, v in d.items():
  12. if k == key and v == value:
  13. ll.append({k: v})
  14. else:
  15. yield from navigate_html(v, key, value, ll)
  16. return ll
  17. for i in navigate_html(d, 'dd', 22):
  18. print('---', i)

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

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

  1. d1={'doctype': ['html'],
  2. 'html': [{'@lang': 'en-EN',
  3. '#text': "ttt",
  4. 'head': [{'#text': 'abc',
  5. 'meta': [{'@charset': 'utf-8', '#text': ''},
  6. {'@name': 'viewport',
  7. '@content': 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no',
  8. '#text': ''},
  9. {'@name': 'description',
  10. '@content': 'cccc',
  11. '#text': '',
  12. 'meta': [{'@name': 'keywords',
  13. '@content': 'cccc',
  14. '#text': ''}]
  15. }]
  16. }]
  17. }]
  18. }

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

答案1

得分: 2

  1. def navigate_html(nested: dict, key, value):
  2. for k, v in nested.items():
  3. if k == key and v == value:
  4. yield {k: v}
  5. elif isinstance(v, list):
  6. for d in v:
  7. if isinstance(d, dict):
  8. yield from navigate_html(d, key, value)
英文:
  1. def navigate_html(nested: dict, key, value):
  2. for k, v in nested.items():
  3. if k == key and v == value:
  4. yield {k: v}
  5. elif isinstance(v, list):
  6. for d in v:
  7. if isinstance(d, dict):
  8. yield from navigate_html(d, key, value)
  9. >>> list(navigate_html(d, 'dd', 22))
  10. # => [{'dd': 22}, {'dd': 22}]
  11. >>> list(navigate_html(d1, '@content', 'cccc'))
  12. # => [{'@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:

确定