0

getting the following error while accesing python

from collections import Counter
alphas = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
res = ''
for char in alphas:
    res = "{0},{1}|{2}".format(res , char, Counter[char])
    print(res)

TypeError: 'type' object is not subscriptable

2
  • Counter is a constructor, not a sequence... plus what is the point of counting a single character one by one in a list? Code doesn't make sense. What are you trying to achieve? Commented Jan 24, 2018 at 8:38
  • I would like to achieve counting characters alone for eg a|23,b|56,...z|12 Commented Jan 24, 2018 at 8:41

1 Answer 1

1

Using the Counter it is a lot easier than what you are trying to achieve:

from collections import Counter

alphas = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
print(Counter(alphas))

And if you want to print them in format of "count|letter" then:

res = ''
counts = Counter(alphas)
for count, letter in counts.items():
    res += '{}|{},'.format(count, letter)

print(res)
Sign up to request clarification or add additional context in comments.

6 Comments

for count, letter in alphas.items(): AttributeError: 'list' object has no attribute 'items'
@praveena sorry mate, I didn't check the code, didn't notice the mistake/semi-typo, but I guess you figured it out now.
This doesn't actually explain from where the original error originated.
@SethMMorton, the original error originated from him/her trying to invoke a function using square brackets and ... functions are objects as everything in python and the resulting error. I don't think the actual goal was to understand the error, but to get the "program" to work.
@AlekseiMaide Yes, I know that. The point is that this answer is only half useful. It does direct the OP in how to do what they actually want, but it does not prevent them from making the same original mistake again, nor give them more insight into Python's object model.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.