In: Computer Science
In python, read the file credit_cards.txt into a dictionary with the count of how many cards of each type of card are in the file.
credit_cards.txt contains the following data:
John Smith, Discover
Helen Jones, Visa
Jerry Jones, Master Card
Julio Jones, Diners Club
Fred Jones, Diners Club
Anthony Rendon, Platinum Visa
Juan Soto, Platinum Visa
George Jones, American Express
Brandon Allen, Visa
Henry Beureguard, Visa
Allen Jackson, Master Card
Faith Hill, Platinum Visa
David Smith, Master Card
Samual Jackson, Visa
Donny Jackson, Master Card
Herb Smith, Visa
Ryan Day, American Express
Herm Edwards, American Express
Daisey Fuentes, Master Card
Henry Flood, Visa
Program Code to Copy:
file = open('credit_cards.txt', 'r') credit_cards = {} clean_lines = [] for i in file: # Filtering out lines that are empty(if line is not blank we take it into another list(clean_lines)) if i != '\n': clean_lines.append(i) file.close() for i in clean_lines: # Splitting the line based on comma(,) and storing the values card_holder_name, card_type = i.split(',') # Removing whitespaces from both the ends card_type = card_type.strip() # If card is in dictionary add one if card_type in credit_cards.keys(): credit_cards[card_type] += 1 # If card is not in dictionary record this entry as first entry else: credit_cards[card_type] = 1 print('Number of Credit Cards of each type is given below\n') for credit_card in credit_cards.keys(): # Storing value of number of cards of each type no_of_cards = credit_cards[credit_card] # Printing a message based on number of cards of given day if no_of_cards > 1: print('There are', no_of_cards, credit_card, 'credit cards') else: print('There is 1', credit_card, 'credit card')
Code Screenshot:
Output Screenshot: