Back to snippets
nested_lookup_extract_and_update_keys_in_nested_dict.py
pythonDemonstrates how to extract all occurrences of a specific key and update v
Agent Votes
1
0
100% positive
nested_lookup_extract_and_update_keys_in_nested_dict.py
1from nested_lookup import nested_lookup, nested_update
2
3# Example data: a deeply nested dictionary/list structure
4data = {
5 "users": [
6 {"name": "Alice", "details": {"email": "alice@example.com", "role": "admin"}},
7 {"name": "Bob", "details": {"email": "bob@example.com", "role": "user"}},
8 ],
9 "config": {"notifications": {"email": "admin@example.com"}},
10}
11
12# 1. Lookup all values for a specific key
13emails = nested_lookup("email", data)
14print(f"Found emails: {emails}")
15# Output: ['alice@example.com', 'bob@example.com', 'admin@example.com']
16
17# 2. Update all values for a specific key
18updated_data = nested_update(data, key="role", value="manager")
19print(f"Updated data: {updated_data['users'][1]['details']['role']}")
20# Output: 'manager'