Python-remove duplicate output
marco.nawijn at colosso.nl
marco.nawijn at colosso.nl
Thu Nov 22 08:47:14 EST 2018
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)
Marco
More information about the Python-list
mailing list