Advanced Techniques
Complex Key Manipulation Strategies
1. Sorting Dictionary Keys
## Sorting keys alphabetically
user_data = {
"zara": 28,
"alice": 35,
"bob": 22,
"charlie": 40
}
## Sort keys in ascending order
sorted_keys = sorted(user_data.keys())
print(sorted_keys) ## Output: ['alice', 'bob', 'charlie', 'zara']
## Sort keys in descending order
reverse_sorted_keys = sorted(user_data.keys(), reverse=True)
print(reverse_sorted_keys) ## Output: ['zara', 'charlie', 'bob', 'alice']
## Key transformation techniques
original_dict = {
"first_name": "John",
"last_name": "Doe",
"age": 30
}
## Convert keys to uppercase
uppercase_keys = [key.upper() for key in original_dict.keys()]
print(uppercase_keys) ## Output: ['FIRST_NAME', 'LAST_NAME', 'AGE']
graph TD
A[Key Extraction Techniques] --> B[Filtering]
A --> C[Transformation]
A --> D[Conditional Extraction]
Nested Dictionary Key Handling
## Complex nested dictionary key extraction
complex_data = {
"department": {
"tech": {"employees": 50},
"sales": {"employees": 30}
},
"company": "LabEx Solutions"
}
## Extract keys from nested structures
nested_keys = list(complex_data.keys()) + list(complex_data["department"].keys())
print(nested_keys) ## Output: ['department', 'company', 'tech', 'sales']
Key Manipulation Techniques
Technique |
Description |
Use Case |
Filtering |
Select specific keys |
Data cleaning |
Mapping |
Transform key names |
Standardization |
Sorting |
Order keys |
Consistent presentation |
Dynamic Key Generation
## Generate keys based on complex logic
def generate_keys(base_dict, prefix=''):
return [f"{prefix}{key}" for key in base_dict.keys()]
sample_dict = {"name": "Alice", "age": 30}
prefixed_keys = generate_keys(sample_dict, 'user_')
print(prefixed_keys) ## Output: ['user_name', 'user_age']
Memory-Efficient Key Handling
## Using generator expressions for large dictionaries
large_dict = {str(i): i for i in range(10000)}
## Memory-efficient key extraction
key_generator = (key for key in large_dict.keys())
first_100_keys = list(next(key_generator) for _ in range(100))
LabEx Pro Tip
When working with complex dictionary key operations, always consider memory usage and performance, especially when dealing with large datasets. Choose the most appropriate technique based on your specific requirements.