Python:移除字典中各键对应的嵌套列表重复项
Hey there, let's fix this duplicate nested list issue in your dictionary. The tricky part here is that regular lists aren't hashable—so we can't just toss them into a set directly to remove duplicates. Instead, we'll convert each sublist to a hashable type (like a tuple), eliminate duplicates, then convert back to lists.
Here's a complete, working code snippet that does exactly what you need, while preserving the original order of your sublists (which matches your target dictionary):
# Your original results dictionary results = {'a': [['1', '2', '4'],['1', '2', '2'],['1', '2', '2']], 'b': [['2', '2', '4'],['2', '2', '2'],['1', '2', '4']], 'c': [['1', '2', '4'],['1', '2', '2'],['1', '2', '2']]} newdict = {} for key, nested_lists in results.items(): # Convert sublists to tuples (hashable) and use dict.fromkeys to keep order unique_tuples = list(dict.fromkeys(tuple(sublist) for sublist in nested_lists)) # Convert tuples back to lists for the final dictionary newdict[key] = [list(tpl) for tpl in unique_tuples] # Check the output print(newdict)
Why this works:
tuple(sublist)converts each inner list to a tuple (since tuples are hashable and can be used as keys in a dictionary)dict.fromkeys()creates a dictionary where each key is a unique tuple, and since dictionaries in Python 3.7+ preserve insertion order, your original sublist order stays intact- We then convert each tuple back to a list to match the structure of your original dictionary
If you're using a Python version older than 3.7 (where dictionaries don't preserve order), you can use OrderedDict from the collections module instead:
from collections import OrderedDict newdict = {} for key, nested_lists in results.items(): unique_tuples = list(OrderedDict.fromkeys(tuple(sublist) for sublist in nested_lists)) newdict[key] = [list(tpl) for tpl in unique_tuples]
Running either of these will give you the exact target dictionary you're looking for:
{'a': [['1', '2', '4'], ['1', '2', '2']], 'b': [['2', '2', '4'], ['2', '2', '2'], ['1', '2', '4']], 'c': [['1', '2', '4'], ['1', '2', '2']]}
内容的提问来源于stack exchange,提问作者my name jeff

