Reputation: 5041
My python code is like this:
d={'abc':'movies', 'abc': 'sports', 'abc': 'music', 'xyz': 'music', 'pqr':'music','pqr':'movies', 'pqr':'sports', 'pqr':'news', 'pqr':'sports'}
b=[j[0] for i in d for j in i.items()]
for k in list(set(b)):
print "{0}: {1}".format(k, b.count(k))
I need to print number of distinct values per each key individually. That means I would want to print
abc 3
xyz 1
pqr 4
I get an error: AttributeError: 'str' object has no attribute 'items'
Please help!
Upvotes: 0
Views: 127
Reputation: 19406
You cannot have duplicate keys in a dictionary in Python:
>>> d = {'abc':'movies', 'abc': 'sports', 'abc': 'music', 'xyz': 'music', 'pqr':'music','pqr':'movies', 'pqr':'sports', 'pqr':'news', 'pqr':'sports'}
>>> print d
{'pqr': 'sports', 'abc': 'music', 'xyz': 'music'}
Upvotes: 1
Reputation: 101909
You can't do that, because each key can appear only once in a dictionary:
>>> d={'abc':'movies', 'abc': 'sports', 'abc': 'music', 'xyz': 'music', 'pqr':'music','pqr':'movies', 'pqr':'sports', 'pqr':'news', 'pqr':'sports'}
>>> d
{'pqr': 'sports', 'abc': 'music', 'xyz': 'music'}
What you want is to have list
s as values:
>>> d = {'abc': ['movies', 'sports', 'music'], 'xyz': ['music'], 'pqr': ['music', 'movies', 'sports', 'news', 'sports']}
>>> d
{'xyz': ['music'], 'abc': ['movies', 'sports', 'music'], 'pqr': ['music', 'movies', 'sports', 'news', 'sports']}
With this representation it's pretty simple to do what you want:
>>> for key, value in sorted(d.items()):
... print key, len(value) #in python3: print(key, len(value))
...
abc 3
pqr 5
xyz 1
If you then want to add a value to a given key simply do:
>>> d['xyz'].append('news')
>>> for key, value in sorted(d.items()):
... print key, len(value)
...
abc 3
pqr 5
xyz 2
Often in this kind of circumstances using a defaultdict
instead of a plain dict
is better.
Upvotes: 7