Removing ' ' and [ ] from list

63 Views Asked by At

I was tasked to take and remove the "and" from in between the "guardians" key within a dictionary. Here's the dictionary nested within the list:

PLAYERS = [{
        'name': 'Karl Saygan',
        'guardians': 'Heather Bledsoe',
        'experience': 'YES',
        'height': '42 inches'
    },
    {
        'name': 'Matt Gill',
        'guardians': 'Charles Gill and Sylvia Gill',
        'experience': 'NO',
        'height': '40 inches'
    },
    {   'name': 'Sammy Adams',
        'guardians': 'Jeff Adams and Gary Adams',
        'experience': 'NO',
        'height': '45 inches'
    },
    {
        'name': 'Chloe Alaska',
        'guardians': 'David Alaska and Jamie Alaska',
        'experience': 'NO',
        'height': '47 inches'
    },
    {
        'name': 'Bill Bon',
        'guardians': 'Sara Bon and Jenny Bon',
        'experience': 'YES',
        'height': '43 inches'
    },
    {
        'name': 'Joe Kavalier',
        'guardians': 'Sam Kavalier and Elaine Kavalier',
        'experience': 'NO',
        'height': '39 inches'
    },
    {
        'name': 'Phillip Helm',
        'guardians': 'Thomas Helm and Eva Jones',
        'experience': 'YES',
        'height': '44 inches'
    }
]

What I did to format it without the ' ' was:

import random
from constants import PLAYERS
from constants import TEAMS

GREETING = 'BASKETBALL TEAM STATS TOOL\n'

players = PLAYERS.copy()
teams = TEAMS.copy()

print(GREETING.upper())


print('-----MENU-----\n')


max_players = len(players)/len(teams)
exp_players = []
nexp_players = []

panthers = []
bandits = []
warriors = []

       
squads = [panthers, bandits, warriors]
num_teams= len(squads)             
            
def balance_teams(players):
    for player in players:
        experience = player['experience']
       
        
        if experience == 'YES':
            exp_players.append(player)
            
        else:
            nexp_players.append(player)  
  


def balance_exp(exp_lists):
    for num in range(len(exp_lists)):
        squads[num % num_teams].append(exp_lists[num])
            
def dis_options():
    print('Here are your Choices: \n A) Display Team Stats \n B) Quit\n\n')
    while max_players > 0:
        try:
            activate = input('Enter an option: ')
            
            if activate.lower() == "a" or activate.lower() == "b":
                
                if activate.lower() == "a":
                    show_teams()
                
                elif activate.lower() == "b":
                    print('Thank you, come back for more basketball stats!')
                    exit()
            else:
                raise ValueError
        
        except ValueError as err:
            print("\nInvalid input.Please choose either A or B\n")
            

    
def show_teams():
    print('\nA)Panthers\n\nB)Bandits\n\nC)Warrirors\n\n')

    try:
        team_sel= input('Enter an option: ')
        if team_sel.lower() == "a" or team_sel.lower()=="b" or team_sel.lower() == "c":
            if team_sel.lower() == "a":
                team = "Panthers"
                members = len(panthers)
                exp_count = 0
                height = []
                for players in panthers:
                    if players['experience']== True:
                        exp_count += 1
                    height.append(players['height'])
                nexp_count = (members - exp_count)
                average_height = (round(sum(height)/members)) 
                
                print('\nTEAM: {} Stats\n--------------------\nTotal Players: {}\nExperienced Players: {}\nNon-experienced Players: {}\nAverage Height: {} inches\n\n'.format(team,members,exp_count,nexp_count, average_height))
                print(pretty_data(*panthers, sep= ','))
               
            elif team_sel.lower() == "b":
                team = "Bandits"
                members = len(bandits) 
                exp_count = 0
                height = []
                for players in bandits:
                    if players['experience']== True:
                        exp_count += 1
                    height.append(players['height'])
                nexp_count = (members - exp_count)
                average_height = (round(sum(height)/members)) 
                
                print('\nTEAM: {} Stats\n--------------------\nTotal Players: {}\nExperienced Players: {}\nNon-experienced Players: {}\nAverage Height: {} inches\n\n'.format(team,members,exp_count,nexp_count, average_height))
                print(pretty_data(*bandits, sep= ','))
            
            elif team_sel.lower() == "c":
                team = "Warriors"
                members = len(warriors)
                exp_count = 0
                height = []
                for players in warriors:
                    if players['experience']== True:
                        exp_count += 1
                    height.append(players['height'])
                nexp_count = (members - exp_count)
                average_height = (round(sum(height)/members)) 
                
                print('\nTEAM: {} Stats\n--------------------\nTotal Players: {}\nExperienced Players: {}\nNon-experienced Players: {}\nAverage Height: {} inches\n\n'.format(team,members,exp_count,nexp_count, average_height))
                print(pretty_data(*warriors, sep= ','))
                
        else:
            raise ValueError
      
    except ValueError as err:
        print("\nInvalid input.Please choose either A, B or C\n")     

def pretty_data(*team, sep= ','):
    for player in team:
        print(f"Name: {player['name']}\nGuardians: {player['guardians']}\nExperience: {player['experience']}\nHeight: {player['height']}\n")
        
if __name__ == '__main__':
    def clean_data():
        for player in players:
            if player['experience'].lower() == 'yes':
                player['experience'] = True
            else:
                player['experience'] = False
            
        for player in players:
            if player['height'] != int():
                player['height'] = int(player['height'].split()[0])
                

            
    
      
    balance_teams(players)
    balance_exp(exp_players)
    balance_exp(nexp_players)
    clean_data()
    dis_options()
    

Next, I needed to remove the and from in between the guardians, I used:

        for player in PLAYERS:
            player['guardians'] = player['guardians'].split(' and ')

The results print like so:

Name: Herschel Krustofski                                                                                                        
Guardians: ['Hyman Krustofski', 'Rachel Krustofski']                                                                             
Experience: True                                                                                                                 
Height: 45                                                                                                                       
                                                                                                                                 
Name: Matt Gill                                                                                                                  
Guardians: ['Charles Gill', 'Sylvia Gill']                                                                                       
Experience: False                                                                                                                
Height: 40                                                                                                                       
                                                                                                                                 
Name: Joe Kavalier                                                                                                               
Guardians: ['Sam Kavalier', 'Elaine Kavalier']                                                                                   
Experience: False                                                                                                                
Height: 39                                                                                                                       
                                                                                                                                 
Name: Eva Gordon                                                                                                                 
Guardians: ['Wendy Martin', 'Mike Gordon']                                                                                       
Experience: False                                                                                                                
Height: 45                       

The brackets and quotes are added back. I tried adding the .split to the pretty_data function but it still included the ' ' and []. Can someone give me guidance?

2

There are 2 best solutions below

0
On

Simple replacement:

player['guardians'] = player ['guardians'].replace(' and ',', ')
6
On

The brackets and quotes are symbols Python is using to denote strings (quotes) and lists (brackets). They aren't being added and you can't take them away. Now, if you just want to print them without seeing the brackets, well that is easy enough.

example = ['Hyman Krustofski', 'Rachel Krustofski'] 
print(f"Guardians: {example}")
print(f"Guardians: {', '.join(example)}")

This yields:

Guardians: ['Hyman Krustofski', 'Rachel Krustofski']
Guardians: Hyman Krustofski, Rachel Krustofski