0

I have been trying to count the values in a dictionary with respect to the key. However, I could not achieved desired result. I will demonstrate with more details below:

from collections import Counter
d = {'a': ['Adam','Adam','John'], 'b': ['John','John','Joel'], 'c': ['Adam','Adam','John}
# create a list of only the values you want to count,
# and pass to Counter()
c = Counter([values[1] for values in d.itervalues()])
print c

My output:

Counter({'Adam': 2, 'John': 1})

I want it to count everything in the list, not just first value of the list. Also, I want my result to be with respect to the key. I will show you my desired output below:

{'a': [{'Adam': 1, 'John': 2}, 'b':{'John': 2, 'Joel': 1}, 'c':{'Adam': 2, 'John': 1 }]}

Is it possible to get this desired output? Or anything close to it? I would like to welcome any suggestions or ideas that you have. Thank you.

2
  • this has been asked a lot of times. Commented Oct 15, 2016 at 10:56
  • Hi Marcus, I have tried to search online for a solution for hours. Unfortunately, I couldn't find it. Could it give me link to it? Thank you. Commented Oct 15, 2016 at 11:43

2 Answers 2

1

Try this using dict comprehension

from collections import Counter
d = {'a': ['Adam','Adam','John'], 'b': ['John','John','Joel'], 'c': ['Adam','Adam','John'}
c = {i:Counter(j) for i,j in d.items()}
print c
Sign up to request clarification or add additional context in comments.

7 Comments

Hi, do you elaborate further? Sorry. I am still new to python. Thank you!
Is it you desired solution? Look at python dict comprehension and docs.python.org/2/library/collections.html#collections.Counter. Its simple
Sorry. I could find information related to dict comprehension based on the link given by you. Did u give me a wrong link?
link that was about Counter. About dict comprehension python.org/dev/peps/pep-0274
I have read about it. This is what I want. But I have no idea how how should i go about doing it? Pardon me. Do you have idea about it? Thank you.
|
1

You're picking only the first elements in the each list with values[1], instead, you want to iterate through each values using a for that follows the first:

>>> from collections import Counter
>>> d = {'a': ['Adam','Adam','John'], 'b': ['John','John','Joel'], 'c': ['Adam','Adam','John']}
>>> Counter([v for values in d.itervalues() for v in values]) # iterate through each value
Counter({'John': 4, 'Adam': 4, 'Joel': 1})

1 Comment

Hi your solution is great. However, is it possible to the outside to produce the result that is linked to the dictionary? For eg {'a': [{'Adam': 1, 'John': 2} Thanks!

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.