Delete « Pasted Segment » from Mailchimp Audience using Marketing API

Sources

Install Mailchimp Marketing API

Python
pip install mailchimp_marketing

Script

Python
import mailchimp_marketing as MailchimpMarketing
from mailchimp_marketing.api_client import ApiClientError

# Initialize the Mailchimp client with your API key and server prefix.
mc_client = MailchimpMarketing.Client()
mc_client.set_config({
    "api_key": "YOUR_MAILCHIMP_API_KEY",  # Replace with your actual Mailchimp API key
    "server": "YOUR_MAILCHIMP_SERVER_PREFIX"  # Replace with your server prefix (e.g., us1, us2, etc.)
})

def mc_segments():
    """
    Retrieves and filters segments from your Mailchimp audience.

    Returns:
        dict: A dictionary where keys are segment IDs and values are lists containing the segment names.
              Contains only segments with names including "Pasted".
    """
    try:
        # Get the ID of the first list in your Mailchimp account.
        # Note: This assumes you only have one list. If you have multiple, you'll need to adjust this.
        get_the_mclist_id = mc_client.lists.get_all_lists()
        idlist = get_the_mclist_id["lists"][0]["id"]

        thisseg = 0  # Initialize a counter for iterating through segments
        segdict = {}  # Initialize a dictionary to store segment IDs and names

        # Fetch up to 450 segments from your Mailchimp list.
        # You might need to adjust the 'count' parameter based on the number of segments in your list.
        get_the_mcsegments = mc_client.lists.list_segments(idlist, count=450)

        # Iterate through the retrieved segments.
        for segid in get_the_mcsegments["segments"]:
            # Check if the segment name contains "Pasted".
            if "Pasted" in get_the_mcsegments["segments"][thisseg]["name"]:
                # If it does, add the segment ID and name to the dictionary.
                segdict[get_the_mcsegments["segments"][thisseg]["id"]] = [get_the_mcsegments["segments"][thisseg]["name"]]
            thisseg += 1  # Increment the counter

        return segdict  # Return the dictionary of segments to be deleted

    except Exception as error:
        print(error)  # Print any errors encountered during the process

# Iterate through the keys (segment IDs) in the dictionary returned by mc_segments().
for key in mc_segments():
    # Delete the segment using the Mailchimp API.
    # Make sure to replace "YOUR_MAILCHIMP_LIST_ID" with your actual list ID.
    response = mc_client.lists.delete_segment("YOUR_MAILCHIMP_LIST_ID", key)
    print(key," : ",response)  # Print the API response (usually a success message if the deletion was successful)