如何使用函数批量标准化未知键名的字典键名
Solution: Normalize Dictionary Keys Dynamically
Since we don’t know the dictionary keys in advance, we can build a reusable key normalization function and apply it to every key-value pair to create a new standardized dictionary. Here’s a straightforward Python implementation:
Step 1: Define the Key Normalization Function
This function handles converting keys to lowercase and replacing spaces/hyphens with underscores. You can choose between two approaches:
Option 1: Using Regex (Concise for Multiple Replacements)
import re def normalize_key(key): # Convert to lowercase, then replace spaces/hyphens with underscores return re.sub(r'[\s-]', '_', key.lower())
Option 2: No Regex (No External Imports)
If you prefer avoiding regex, chain string replace methods:
def normalize_key(key): return key.lower().replace(' ', '_').replace('-', '_')
Both methods will produce identical results for your use case.
Step 2: Generate the Normalized Dictionary
Use a dictionary comprehension to iterate over the original dictionary, apply the normalization function to each key, and map to the original value:
d1 = { 'a b':1, 'c-d':2, 'Ef':3 } # Create the new dictionary with normalized keys d2 = { normalize_key(old_key): value for old_key, value in d1.items() } print(d2) # Output: {'a_b': 1, 'c_d': 2, 'ef': 3}
Key Benefits of This Approach
- Dynamic Handling: Works for any number of unknown keys—no need to hardcode key names.
- Reusability: The
normalize_keyfunction can be extended easily (e.g., add rules to remove special characters) without rewriting core logic. - Safety: We create a new dictionary instead of modifying the original, avoiding bugs from iterating over a changing object.
内容的提问来源于stack exchange,提问作者Anonymous Entity
相关产品推荐
相关产品推荐

