Let's say I have a long list of this type:
text = [ ['a', 'b'], ['a', 'd'], ['w', 'a'], ['a', 'b'], ... ]
Given the first elements, I want to construct a dictionary that would show a count of the second elements. For example in the particular example above, I'd like to have something like this:
{'a': {'b':2, 'd':1},
'w': {'a':1}
}
Here's how I unsuccessfully tried to solve it. I constructed a list of unique first elements. Let's call it words
and then:
dic = {}
for word in words:
inner_dic = {}
for pair in text:
if pair[0] == word:
num = text.count(pair)
inner_dic[pair[1]] = num
dic[pair[0]] = inner_dic
I get an obviously erroneous result. One problem with the code is, it overcounts pairs. I am not sure how to solve this.