I have the following tuple.I want to build a string which outputs as stated in output.I want count all the elements corresponding to ‘a’ i.e, how many k1 occured w.r.t ‘a’ and so on .What is the easiest way to do this
a=[('a','k1'),('b','k2'),('a','k2'),('a','k1'),('b','k2'),('a','k1'),('b','k2'),('c','k3'),('c','k4')]
Output should be in a string output=””
a k1 3
a k2 1
b k1 1
b k2 3
c k3 1
c k4 1
You can do the addition portion easily with defaultdict. The default dict works like a normal dictionary, except it has a default value for empty key stores so you can easily increment your counter when you iterate over your data set.
And for pretty printing it, just iterate over the resulting data and print it how you want.