Unique list of dicts in python function

Python -- Posted on Dec. 3, 2024

Python function to create a list of unuque dicts

              
                def unique_items(keys, objects):
    # Extract relevant items based on keys and create frozensets for uniqueness
    items = [{key: obj[key] for key in keys if key in obj} for obj in objects]
    # Use frozenset to ensure uniqueness
    set_of_dicts = {frozenset(d.items()) for d in items}
    # Convert back to dictionaries for easier usability
    unique_dicts = [dict(s) for s in set_of_dicts]
    print(len(unique_dicts))
    return unique_dicts
                  
   
            

Related Posts