Home > front end >  How do I remove newline from my key in a dictionary?
How do I remove newline from my key in a dictionary?

Time:11-10

I have a file I am reading from and putting it into a dictionary. How do I remove the new line from the key?

def main():

    # Set up empty dictionary
    counter = {}

    # open text file
    my_file = open("WorldSeriesWinners.txt", "r")
    words = my_file.readlines()

    # Add each unique word to dictionary with a counter of 0
    unique_words = list(set(words))
    for word in unique_words:
        counter[word] = 0

    # For each word in the text increase its counter in the dictionary
    for item in words:
        counter[item]  = 1

    return counter

counter = main()
print(counter)

OUTPUT:

{'Cleveland Indians\n': 2, 'Pittsburgh Pirates\n': 5, 'St. Louis Cardinals\n': 10, 'New York Giants\n': 5, 'Cincinnati Reds\n': 5, 'Boston Americans\n': 1, 'Chicago White Sox\n': 3, 'Toronto Blue Jays\n': 2, 'Detroit Tigers\n': 4, 'NONE\n': 2, 'Boston Red Sox\n': 6, 'Minnesota Twins\n': 2, 'Kansas City Royals\n': 1, 'Chicago Cubs\n': 2, 'Baltimore Orioles\n': 3, 'Arizona Diamondbacks\n': 1, 'Philadelphia Phillies': 1, 'Los Angeles Dodgers\n': 5, 'Brooklyn Dodgers\n': 1, 'Florida Marlins\n': 2, 'Washington Senators\n': 1, 'New York Yankees\n': 26, 'Philadelphia Athletics\n': 5, 'Boston Braves\n': 1, 'New York Mets\n': 2, 'Atlanta Braves\n': 1, 'Anaheim Angels\n': 1, 'Philadelphia Phillies\n': 1, 'Oakland Athletics\n': 4, 'Milwaukee Braves\n': 1}

CodePudding user response:

Just use the replace function when defining your key. See below:

def main():

    # Set up empty dictionary
    counter = {}

    # open text file
    my_file = open("WorldSeriesWinners.txt", "r")
    words = my_file.readlines()

    # Add each unique word to dictionary with a counter of 0
    unique_words = list(set(words))
    for word in unique_words:
        word_no_lines = word.replace('\n', '')
        counter[word_no_lines] = 0

    # For each word in the text increase its counter in the dictionary
    for item in words:
        item_no_lines = item.replace('\n', '')
        counter[item_no_lines]  = 1

    return counter

counter = main()
print(counter)
  • Related