I have multiple lists like below
[u'a', 11, u'P']
[u'a', 11, u'A']
[u'b', 2, u'P']
[u'c', 1, u'P']
[u'c', 2, u'P']
[u'd', 1, u'P']
[u'e', 3, u'P']
[u'f', 2, u'P']
[u'a', 1, u'P']
[u'a', 2, u'P']
[u'b', 1, u'P']
[u'b', 11, u'P']
how to merge above lists,to loop the list to add up like below
[u'a', 11, u'P'] + [u'a', 2, u'P'] + [u'a', 11, u'A'] = ['a',('P' : 13) ,('A': 11)]
[u'b', 2, u'P'] + [u'b', 1, u'P'] + [u'b', 11, u'P'] = ['b',14,p]
output should like below :
['a',('P' : 13) ,('A': 11)]
['b',14,'p']
The output that you want looks slightly strange due to the inconsistency between the two cases. You could trivially change this example to get whatever output you want, however:
The output is:
Update: Thanks to sharjeel for suggesting in the comment below that I remove the
setdefaultby usingdefaultdictinstead.Update 2: In your further question in the comments below, you indicate that instead you want as output “[a] set of lists like
[[u'a', 11, u'P'], [u'a', 11, u'A']“. (I’m assuming for the moment that you mean a list of lists rather than a set, but that’s almost as easy.) In order to construct such a list of lists , you could replace the loop that prints the values with the following:… which will give the output: