Python技术实现:将IMAP返回的元组列表转换为字典
Hey there! Let's turn that IMAP folder tuple list into a clean, nested dictionary that shows the folder hierarchy and their child status clearly. Here's a step-by-step solution:
First, let's break down the input structure: each entry is a tuple containing flags (like b'\\HasChildren'), the folder delimiter (here it's .), and the full folder path string. Our goal is to map these into a nested dict where each folder has its has_children status and a sub-dict of its child folders.
Here's the Python code to do this:
# Your raw IMAP folder list from imap.list_folders() imap_folders = [ ((b'\\HasChildren',), b'.', 'welcome'), ((b'\\HasChildren',), b'.', 'welcome.welcomeqqqqq'), ((b'\\HasNoChildren',), b'.', 'welcome.welcomeqqqqq.downunder'), ((b'\\HasNoChildren',), b'.', 'test2'), ((b'\\HasNoChildren',), b'.', 'Arunnnnnnnnn') ] def imap_folders_to_nested_dict(folders): root = {} for flags, delimiter, folder_path in folders: # Convert bytes delimiter to string for path splitting delim = delimiter.decode('utf-8') # Split the full folder path into individual hierarchy levels folder_hierarchy = folder_path.split(delim) # Check if the current folder has child folders has_kids = b'\\HasChildren' in flags # Traverse or build the nested structure current_node = root # Navigate through each level except the final folder for folder in folder_hierarchy[:-1]: # Create the folder node if it doesn't exist yet if folder not in current_node: current_node[folder] = {'has_children': True, 'children': {}} # Move down to the child level current_node = current_node[folder]['children'] # Add the final folder in the hierarchy final_folder = folder_hierarchy[-1] current_node[final_folder] = { 'has_children': has_kids, 'children': {} if has_kids else None } return root # Generate the structured dictionary folder_structure = imap_folders_to_nested_dict(imap_folders) # To visualize the result nicely, use json.dumps import json print(json.dumps(folder_structure, indent=2))
When you run this, you'll get a structured output like this:
{ "welcome": { "has_children": true, "children": { "welcomeqqqqq": { "has_children": true, "children": { "downunder": { "has_children": false, "children": null } } } } }, "test2": { "has_children": false, "children": null }, "Arunnnnnnnnn": { "has_children": false, "children": null } }
A few quick notes:
- We use a dictionary for
childrenso you can easily look up subfolders by name. If you prefer a list instead, you can adjust the code to append to a list instead of setting keys, but a dict is more practical for folder lookups. - The
has_childrenflag is directly mapped from the IMAP server's response, so it's accurate to what the server reported. - We handle byte-to-string conversion for the delimiter to avoid issues when splitting the folder path.
Feel free to tweak the structure (like changing children: null to children: [] for empty folders) if that better fits your use case. Hope this helps!
内容的提问来源于stack exchange,提问作者Arun

