Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Sure! Here's a Python function that can handle the nested list of dictionaries and a query string to retrieve the corresponding value:
- ```python
- def query_nested_dicts(data, query_string):
- keys = query_string.split('.')
- value = data
- for key in keys:
- if isinstance(value, dict):
- value = value.get(key)
- elif isinstance(value, list):
- value = [item.get(key) if isinstance(item, dict) else None for item in value]
- else:
- value = None
- break
- return value
- ```
- Let's see how you can use this function with an example:
- ```python
- data = [
- {
- 'name': 'John',
- 'age': 25,
- 'address': {
- 'street': '123 Main St',
- 'city': 'New York',
- 'country': 'USA'
- }
- },
- {
- 'name': 'Alice',
- 'age': 30,
- 'address': {
- 'street': '456 Elm St',
- 'city': 'San Francisco',
- 'country': 'USA'
- }
- }
- ]
- query = 'address.city'
- result = query_nested_dicts(data, query)
- print(result)
- ```
- Output:
- ```
- ['New York', 'San Francisco']
- ```
- 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.
- 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.
- 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