I have a python dict that I am trying to work out the frequency of which a value is listed.
I cannot import any additional classes so effectively need to write it from scratch. So I have a dict() of
1: Dog, 2: Cat, 3: Dog, 4: Elephant
And I want to return something like:-
2: Dog, 1: Cat, 1:Elephant
This is what I have so far but I cannot work out how to get a count to work. I keep getting
0: Dog, 0: Cat, 0: Elephant
This is what I have so far, could someonle please tell me where I am going wrong?
It's obviously something to do with my count statement (this is just something that I found online but it clearly doesn't work.
I create a empty dict and then add values (animals) to it along with a corresponding key. I then need to go through all the values in all the keys to return the frequency.
The input is a dict() object that contains the values listed of 1: Dog, 2: Cat, 3: Dog, 4: Elephant
def frequency(self):
result = set()
for i in self.items:
result.add((self.count(i), self.items[i]))
return sorted(result)
suppose your dictionary is named d
and you want a count of the values:
from collections import Counter
d = {1: "dog", 2: "cat", 3: "dog", 4: "elephant"}
counts = Counter(d.values())
Now you can use the counts
Counter:
counts['dog'] # 2
counts['elephant'] # 1
counts['fish'] # 0
If you must use custom code and classes for this instead of the standard library, I think your error is here:
result.add((self.count(i), self.items[i]))
What you may want is:
animal_name = self.items[i] #?
result.add((self.count(animal_name), animal_name))
Otherwise you may want to share with us what is in self.items
...
d = {1:"Dog",2:"Cat", 3:"Dog", 4:"Elephant"}
count = {}
for v in d.values():
if(not(v in count)):
count[v] = 0
count[v] += 1
print(count)
{'Dog': 2, 'Cat': 1, 'Elephant': 1}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.