osdir.com

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Python-remove duplicate output


On Nov 22, 2018 8:50 AM, <marco.nawijn at colosso.nl> wrote:
>
> On Thursday, November 22, 2018 at 12:10:28 AM UTC+1, drvuc... at gmail.com
wrote:
> > How to remove duplicate lines and store output into one ine
> >
> >    reservations = ec.describe_instances().get('Reservations', [])
> >
> >    for reservation in reservations:
> >         for instance in reservation['Instances']:
> >             tags = {}
> >             for tag in instance['Tags']:
> >                 tags[tag['Key']] = tag['Value']
> >                 if tag['Key'] == 'Name':
> >                     name=tag['Value']
> >
> >             if not 'Owner' in tags or tags['Owner']=='unknown' or
tags['Owner']=='Unknown':
> >                 print name
> >
> > Current Output:
> >
> > aws-opsworks
> >
> > aws-opsworks Ansible
> >
> > Desired output:
> >
> > aws-opsworks Ansible
>
> You can use a set to do the job. Remember that members in the set are
unique,
> duplicate members are ignored.
>
> Before you start the for loop, create a set:
>
> names = set()
>
> Instead of `print name`, you add the name to the set:
>
> names.add(name)
>
> Note that if name already exists, because members of a set are unique,
> the name is (at least conceptually) ignored.
>
> Once the for loop is completed, you print the remaining names.
>
> print names (Python 2)
> or
> print(names) (Python 3)

It is actually sufficient to just say print)names) since that works equally
well in 2 or 3.

Bob