1

I'm trying to figure how to get how many of each item is in a string. Like for example:

{"harley": ["apple", "apple", "banana"]}

So how would I get this:

Harley has Apple x 2 and Banana x 1
Ashwini Chaudhary
  • 217,951
  • 48
  • 415
  • 461

2 Answers2

2
from collections import Counter

d = {"harley": ["apple", "apple", "banana"]}
for k,v in d.items():
    print("%s has %s" %(k, ', '.join("%s x %s"%(k,v) for k,v in Counter(v).items())))
inspectorG4dget
  • 97,394
  • 22
  • 128
  • 222
2
d = {"harley": ["apple", "apple", "banana"]}

from collections import Counter
for k,v in d.iteritems():
    print k + ' has ' + ' and '.join('{0} x {1}'.format(name, count) for name, count in Counter(v).iteritems())
Eelco Hoogendoorn
  • 9,321
  • 1
  • 39
  • 38