Home > Enterprise >  python: how to only pull unique values from the output of a for loop
python: how to only pull unique values from the output of a for loop

Time:03-10

I am just learning Python. I have a dictionary with a key with with lists in the value. I need to do a count of all the unique values from the key of 'crafts'. I did a loop to get the the 'craft' key but don't know how to only return the unique crafts. Actually want to list them and then do a count of them. Here is what I have so far:

import requests 

Data = { } #create the dictionary

response = requests.get("http://api.open-notify.org/astros.json")

Data = response.json()

for i in range(len(Data["people"])):
    print(Data["people"][i]["craft"])

This is the output:

ISS
ISS
ISS
Shenzhou 13
Shenzhou 13
Shenzhou 13
ISS
ISS
ISS
ISS

What i want to show is:

ISS
Shenzhou 13

and then a count of these with a result of: 2

CodePudding user response:

Here is something that should work out

response = requests.get("http://api.open-notify.org/astros.json")

data = response.json()

unique_crafts = []
for people in data["people"]: 
    craft = people["craft"]
    if craft not in unique_crafts:
        unique_crafts.append(craft)

print(unique_crafts)
print(len(unique_crafts))

CodePudding user response:

Put all the crafts in a set. Sets only contain unique elements.

crafts = set(person['craft'] for person in Data['people'])
print(*crafts, sep='\n')
print(len(crafts))
  • Related