Python 3.6嵌套字典动态更新:将特定格式文件转为嵌套字典
First, let's restate the input format we're working with (each line has a slash-separated key path and a value, split by a semicolon):
HP;1
MN;stringval
IS/VD1;32.00
IS/HD1;1.34
IS/E/ID;362.0000000
IS/OLVD;0.0000000
ISN/I/HFD;3283.8999023
D1/I/MF;7.3059464
D1/I/P;32.0388412
D1/E/E;2778.4829102
D1/S1/SB/I/P;32.0388412
EN;5145
Step-by-Step Implementation
We'll create a helper function to dynamically update the nested dictionary, plus logic to process each line and handle value type conversion (so numbers are stored as integers/floats instead of strings).
Code Implementation
def update_nested_dict(outer_dict, key_path, value): # Split the slash-separated key path into individual keys keys = key_path.split('/') # Traverse to the parent level of the final key current_dict = outer_dict for key in keys[:-1]: # Create the nested dict if it doesn't exist yet current_dict = current_dict.setdefault(key, {}) # Convert value to appropriate type (int > float > string) try: final_value = int(value) except ValueError: try: final_value = float(value) except ValueError: final_value = value.strip() # Set the final value at the deepest key level current_dict[keys[-1]] = final_value # Process input lines (replace with file reading logic if needed) input_lines = [ "HP;1", "MN;stringval", "IS/VD1;32.00", "IS/HD1;1.34", "IS/E/ID;362.0000000", "IS/OLVD;0.0000000", "ISN/I/HFD;3283.8999023", "D1/I/MF;7.3059464", "D1/I/P;32.0388412", "D1/E/E;2778.4829102", "D1/S1/SB/I/P;32.0388412", "EN;5145" ] # Initialize empty nested dictionary nested_dict = {} # Process each line to populate the dictionary for line in input_lines: if ';' not in line: continue # Skip lines without valid key-value split # Split only once to handle values that might contain semicolons key_part, value_part = line.split(';', 1) update_nested_dict(nested_dict, key_part.strip(), value_part.strip()) # Print the result with pretty formatting import pprint pprint.pprint(nested_dict)
How It Works
update_nested_dictFunction:- Splits the key path (like
IS/E/ID) into a list of keys:["IS", "E", "ID"] - Uses
setdefaultto safely traverse or create nested dictionaries at each level (no need for messy conditional checks) - Converts the value to the most appropriate type: first tries integer, then float, falls back to string if neither works
- Splits the key path (like
Main Processing Loop:
- Iterates over each input line, skipping any invalid lines that lack a semicolon
- Splits each line into key path and value (only splits once, so values with semicolons are preserved)
- Calls the helper function to build out the nested dictionary incrementally
Sample Output
When you run the code, you'll get this properly structured nested dictionary:
{'D1': {'E': {'E': 2778.4829102}, 'I': {'MF': 7.3059464, 'P': 32.0388412}, 'S1': {'SB': {'I': {'P': 32.0388412}}}}, 'EN': 5145, 'HP': 1, 'IS': {'E': {'ID': 362.0}, 'HD1': 1.34, 'OLVD': 0.0, 'VD1': 32.0}, 'ISN': {'I': {'HFD': 3283.8999023}}, 'MN': 'stringval'}
Reading from a File
If your data is stored in a file, replace the input_lines list with this file reading code:
with open('your_file.txt', 'r') as file: input_lines = file.read().splitlines()
内容的提问来源于stack exchange,提问作者Giuseppe Salerno

