Python Forum
Count in Dictionaries
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Count in Dictionaries
#1
This is the task that has to completed by using a dictionary of some sort.

You are curious about the most popular and least popular colours of cars and decide to write a program to calculate the frequency of car colours.

Your program should read in the colour of each car until a blank line is entered, and then print out (in any order) all the different colours of car with counts.

For example:

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

Here is another example:


Output:
Car: red Car: white Car: white Car: red Car: white Car: white Car: white Car: Cars that are red: 2 Cars that are white: 5 ​
This is what I have done:

dictionary={}
values=[]
unique=[]
colour=input('Car: ')
values.append(colour)
dictionary['car']=colour


while colour != '':
  colour=input('Car: ')
  values.append(colour)
  dictionary[colour]=' '
print(dictionary)
values=set(values)
values=list(values)


for i in values:
  if i != "":
    unique.append(i)
print(unique)


for i in unique:
  a=((i in dictionary).count())
And this is the output including some inputs that I have provided:

Output:
Car: a Car: s Car: d Car: a Car: a Car: {'car': 'a', 's': ' ', 'd': ' ', 'a': ' ', '': ' '} ['a', 's', 'd']
Error:
Traceback (most recent call last): File "program.py", line 25, in <module> a=((i in dictionary).count()) AttributeError: 'bool' object has no attribute 'count'
I need to count the unique values and print how many times they appear. Please help.
Reply
#2
You seem to be overthinking things a bit.
The dictionary will hold numbers. Increment the count corresponding to that colour ever input.
Then just iterate through the dictionary and print.
colour = input('Car: ')
while colour != "":
  dictionary[colour] = dictionary.get(colour, 0) + 1
  colour = input('Car: ')
Reply
#3
for colour,number in dictionary.items():
    print 'cars that are %s: %d'%(colour,number)
continuation from Mekire's codes to print out the last 2 lines. i'm in python 2.7 just in case error occured
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Count Letters in a Sentence (without using the Count Function) bhill 3 5,065 Jun-19-2018, 02:52 AM
Last Post: bhill

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020