如何将包含字典键值对格式字符串的列表转换为字典?
Got it, let's fix this for you. The problem with your current code has two main issues: first, Python strings are immutable—when you call replace(), it returns a new string instead of modifying the original one (so you weren't actually saving the changes). Second, deleting colons was the wrong approach entirely—we need that colon to split each entry into its key and value pair.
Step-by-Step Fix
Here's a straightforward way to parse your list into a proper dictionary:
- Clean up each string entry: Replace the HTML-escaped
"with actual double quotes, and strip off any trailing commas or newlines that are cluttering the entries. - Split key and value: Use
split(':', 1)to split each cleaned string only once (this keeps values intact even if they had colons, though your sample data doesn't have this issue). - Trim extra whitespace/quotes: Remove any leftover spaces and surrounding quotes from both the key and value.
- Build the dictionary: Add each cleaned key-value pair to your result dictionary.
Full Working Code
# Your original raw data raw_list = ['"acetic anydride": "[CX3](=[OX1])[OX2][CX3](=[OX1])", ', '"acetylenic carbon": "[$([CX2]#C)]", ', '"acyl bromide": "[CX3](=[OX1])[Br]", ', '"acyl chloride": "[CX3](=[OX1])[Cl]", ', '"acyl fluoride": "[CX3](=[OX1])[F]", ', '"acyl iodide": "[CX3](=[OX1])[I]", ', '"aldehyde": "[CX3H1](=O)[#6]", ', '"alkane": "[CX4]", ', '"allenic carbon": "[$([CX2](=C)=C)]", ', '"amide": "[NX3][CX3](=[OX1])[#6]", ', '"amidium": "[NX3][CX3]=[NX3+]", ', '"amino acid": "[$([NX3H2,NX4H3+]),$([NX3H](C)(C))][CX4H]([*])[CX3](=[OX1])[OX2H,OX1-,N]", ', '"azide": "[$(-[NX2-]-[NX2+]#[NX1]),$(-[NX2]=[NX2+]=[NX1-])]", ', '"azo nitrogen": "[NX2]=N", ', '"azole": "[$([nr5]:[nr5,or5,sr5]),$([nr5]:[cr5]:[nr5,or5,sr5])]", ', '"azoxy nitrogen": "[$([NX2]=[NX3+]([O-])[#6]),$([NX2]=[NX3+0](=[O])[#6])]", ', '"diazene": "[NX2]=[NX2]", ', '"diazo nitrogen": "[$([#6]=[N+]=[N-]),$([#6-]-[N+]#[N])]", ', '"bromine": "[Br]", '] # Initialize empty dictionary chemical_dict = {} for entry in raw_list: # Skip any empty or whitespace-only entries if not entry.strip(): continue # Replace escaped quotes and clean trailing commas/newlines cleaned_entry = entry.replace('"', '"').rstrip(',\n') # Split into key and value (only split on the first colon) key_segment, value_segment = cleaned_entry.split(':', 1) # Trim whitespace and surrounding quotes from key and value key = key_segment.strip().strip('"') value = value_segment.strip().strip('"') # Add to the dictionary chemical_dict[key] = value # Test the result print(chemical_dict["aldehyde"]) # Output: [CX3H1](=O)[#6]
Why Your Original Code Failed
Your loop didn't modify the strings because you didn't assign the result of replace() back to a. Even if you had, deleting colons would have destroyed the separation between keys and values—making it impossible to parse them correctly.
内容的提问来源于stack exchange,提问作者Morgenstern

