i have a tuple like this
[
(379146591, 'it', 55, 1, 1, 'NON ENTRARE', 'NonEntrate', 55, 1),
(4746004, 'it', 28, 2, 2, 'NON ENTRARE', 'NonEntrate', 26, 2),
(4746004, 'it', 28, 2, 2, 'TheBestTroll Group', 'TheBestTrollGroup', 2, 3)
]
[
(379146591, (('it', 55, 1, 1, 'NON ENTRARE', 'NonEntrate', 55, 1)),
(4746004, (('it', 28, 2, 2, 'NON ENTRARE', 'NonEntrate', 26, 2), ('it', 28, 2, 2, 'TheBestTroll Group', 'TheBestTrollGroup', 2, 3)))
]
for i in data:
# getting the first element of the list
for sub_i in i[1]:
# i access all the tuples inside
It's pretty simple with defaultdict
; You initialize the default value to be a list and then append the item to the value of the same key:
lst = [
(379146591, 'it', 55, 1, 1, 'NON ENTRARE', 'NonEntrate', 55, 1),
(4746004, 'it', 28, 2, 2, 'NON ENTRARE', 'NonEntrate', 26, 2),
(4746004, 'it', 28, 2, 2, 'TheBestTroll Group', 'TheBestTrollGroup', 2, 3)
]
from collections import defaultdict
d = defaultdict(list)
for k, *v in lst:
d[k].append(v)
list(d.items())
#[(4746004,
# [('it', 28, 2, 2, 'NON ENTRARE', 'NonEntrate', 26, 2),
# ('it', 28, 2, 2, 'TheBestTroll Group', 'TheBestTrollGroup', 2, 3)]),
# (379146591, [('it', 55, 1, 1, 'NON ENTRARE', 'NonEntrate', 55, 1)])]
If order is important, use an OrderedDict
which can remember the insertion orders:
from collections import OrderedDict
d = OrderedDict()
for k, *v in lst:
d.setdefault(k, []).append(v)
list(d.items())
#[(379146591, [['it', 55, 1, 1, 'NON ENTRARE', 'NonEntrate', 55, 1]]),
# (4746004,
# [['it', 28, 2, 2, 'NON ENTRARE', 'NonEntrate', 26, 2],
# ['it', 28, 2, 2, 'TheBestTroll Group', 'TheBestTrollGroup', 2, 3]])]