pythondictionarygrok

Grok help - 2 dictionaries car colors


I've seen other more in-depth solutions to this but as I'm still learning python I want to understand my mistakes.

My code as of now is:

carlist = []
colour = []
while colour != '':
  colour = input("Car: ")
  if colour != '':
    carlist.append(colour)
carlist.sort()
for i in carlist:
  print("Cars that are", i + ":", carlist.count(i))

and outputs:

Car: red
Car: white
Car: blue
Car: green
Car: white
Car: silver
Car:
Cars that are blue: 1
Cars that are green: 1
Cars that are red: 1
Cars that are silver: 1
Cars that are white: 2
Cars that are white: 2

I understand the basics of the problem that I have 2 'white' in my dictionary but where/ how can I fix this?

(also I understand I should format all answers lowercase)


Solution

  • Code: By dictionary()

    carlist=[]
    colour=[]
    while colour != '':
      colour = input("Car: ")
      if colour != '':
        carlist.append(colour)
    
    #Creating a dictionary
    color_counts = {}
    for color in carlist:
        color_counts[color]=color_counts.get(color,0)+1
      
    for color,count in sorted(color_counts.items()): #Sorted dictionary on the basis of key.
      print("Cars that are", color + ":", count)
    

    Code: By set()

    carlist=[]
    colour=[]
    while colour != '':
      colour = input("Car: ")
      if colour != '':
        carlist.append(colour)
    
    for car in sorted(set(carlist)): #firstly set() will remove duplicates and than it will sort.
      print("Cars that are", car + ":", carlist.count(car))
    

    Output: [Both Codes]

    Car: red
    Car: white
    Car: blue
    Car: green
    Car: white
    Car: silver
    Car: 
    Cars that are blue: 1
    Cars that are green: 1
    Cars that are red: 1
    Cars that are silver: 1
    Cars that are white: 2