I'm trying to check how many times a digit appears in a dictionary.
This code only works if I input a single digit.
numbers = input("Enter numbers ")
d = {}
d['0'] = 0
d['1'] = 0
d['2'] = 0
d['3'] = 0
d['4'] = 0
d['5'] = 0
d['6'] = 0
d['7'] = 0
d['8'] = 0
d['9'] = 0
for i in numbers:
d[numbers] += 1
print(d)
For example if I input 8
the output will be
{'8': 1, '9': 0, '4': 0, '5': 0, '6': 0, '7': 0, '0': 0, '1': 0, '2': 0, '3': 0}
But if I input 887655
then it gives me a builtins.KeyError: '887655'
If I input 887655
the output should actually be
{'8': 2, '9': 0, '4': 0, '5': 2, '6': 1, '7': 1, '0': 0, '1': 0, '2': 0, '3': 0}
Use collections.Counter
for this instead - no need to reinvent the wheel.
>>> import collections
>>> collections.Counter("887655")
Counter({'8': 2, '5': 2, '6': 1, '7': 1})
You should probably change
d[numbers] += 1
=>
d[i] += 1
I think what you want is actually this:
for number in numbers:
for digit in str(number):
d[digit] += 1
You should use collections.Counter
from collections import Counter
numbers = input("Enter numbers: ")
count = Counter(numbers)
for c in count:
print c, "occured", count[c], "times"
I would recommend collections.Counter
but here's an improved version of your code:
numbers = input("Enter numbers ")
d = {} # no need to initialize each key
for i in numbers:
d[i] = d.get(i, 0) + 1 # we can use dict.get for that, default val of 0
print(d)
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.