Advertisement
alyandon

Untitled

May 31st, 2023
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. Sure! Here's a Python function that can handle the nested list of dictionaries and a query string to retrieve the corresponding value:
  2.  
  3. ```python
  4. def query_nested_dicts(data, query_string):
  5. keys = query_string.split('.')
  6. value = data
  7.  
  8. for key in keys:
  9. if isinstance(value, dict):
  10. value = value.get(key)
  11. elif isinstance(value, list):
  12. value = [item.get(key) if isinstance(item, dict) else None for item in value]
  13. else:
  14. value = None
  15. break
  16.  
  17. return value
  18. ```
  19.  
  20. Let's see how you can use this function with an example:
  21.  
  22. ```python
  23. data = [
  24. {
  25. 'name': 'John',
  26. 'age': 25,
  27. 'address': {
  28. 'street': '123 Main St',
  29. 'city': 'New York',
  30. 'country': 'USA'
  31. }
  32. },
  33. {
  34. 'name': 'Alice',
  35. 'age': 30,
  36. 'address': {
  37. 'street': '456 Elm St',
  38. 'city': 'San Francisco',
  39. 'country': 'USA'
  40. }
  41. }
  42. ]
  43.  
  44. query = 'address.city'
  45. result = query_nested_dicts(data, query)
  46. print(result)
  47. ```
  48.  
  49. Output:
  50. ```
  51. ['New York', 'San Francisco']
  52. ```
  53.  
  54. In the example above, we have a nested list of dictionaries stored in the `data` variable. The `query` string is set to `'address.city'`, indicating that we want to retrieve the value of the `city` key within the `address` key in each dictionary.
  55.  
  56. The `query_nested_dicts` function splits the query string into individual keys and iterates over the data structure accordingly. It checks if the current value is a dictionary or a list and retrieves the value for the current key. If the value is a list of dictionaries, it retrieves the corresponding values for each item.
  57.  
  58. Finally, the function returns a list of all the values found for the given query.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement