Merge a a tuple with the same key

Clash Royale CLAN TAG#URR8PPP
up vote
6
down vote
favorite
How to merge a tuple with the same key
list_1 = [("AAA", [123]), ("AAA", [456]), ("AAW", [147]), ("AAW", [124])]
and turn them into
list_2 = [("AAA", [123, 456]), ("AAW", [147, 124])]
python
New contributor
Theprofessor14 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |Â
up vote
6
down vote
favorite
How to merge a tuple with the same key
list_1 = [("AAA", [123]), ("AAA", [456]), ("AAW", [147]), ("AAW", [124])]
and turn them into
list_2 = [("AAA", [123, 456]), ("AAW", [147, 124])]
python
New contributor
Theprofessor14 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
Related: Python: merge lists of tuples based on its values
â Aran-Fey
1 hour ago
1
all those years and not a single exact dupe... I had a good look. Maybe it's somewhere, well...
â Jean-François Fabre
1 hour ago
add a comment |Â
up vote
6
down vote
favorite
up vote
6
down vote
favorite
How to merge a tuple with the same key
list_1 = [("AAA", [123]), ("AAA", [456]), ("AAW", [147]), ("AAW", [124])]
and turn them into
list_2 = [("AAA", [123, 456]), ("AAW", [147, 124])]
python
New contributor
Theprofessor14 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
How to merge a tuple with the same key
list_1 = [("AAA", [123]), ("AAA", [456]), ("AAW", [147]), ("AAW", [124])]
and turn them into
list_2 = [("AAA", [123, 456]), ("AAW", [147, 124])]
python
python
New contributor
Theprofessor14 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Theprofessor14 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
edited 1 hour ago
Akshay Nevrekar
2,16851331
2,16851331
New contributor
Theprofessor14 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
asked 1 hour ago
Theprofessor14
312
312
New contributor
Theprofessor14 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Theprofessor14 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Theprofessor14 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
Related: Python: merge lists of tuples based on its values
â Aran-Fey
1 hour ago
1
all those years and not a single exact dupe... I had a good look. Maybe it's somewhere, well...
â Jean-François Fabre
1 hour ago
add a comment |Â
1
Related: Python: merge lists of tuples based on its values
â Aran-Fey
1 hour ago
1
all those years and not a single exact dupe... I had a good look. Maybe it's somewhere, well...
â Jean-François Fabre
1 hour ago
1
1
Related: Python: merge lists of tuples based on its values
â Aran-Fey
1 hour ago
Related: Python: merge lists of tuples based on its values
â Aran-Fey
1 hour ago
1
1
all those years and not a single exact dupe... I had a good look. Maybe it's somewhere, well...
â Jean-François Fabre
1 hour ago
all those years and not a single exact dupe... I had a good look. Maybe it's somewhere, well...
â Jean-François Fabre
1 hour ago
add a comment |Â
5 Answers
5
active
oldest
votes
up vote
5
down vote
The most performant approach is to use a collections.defaultdict dictionary to store data as an expanding list, then convert back to tuple/list if needed:
import collections
list_1 = [("AAA", [123]), ("AAA", [456]), ("AAW", [147]), ("AAW", [124])]
c = collections.defaultdict(list)
for a,b in list_1:
c[a].extend(b) # add to existing list or create a new one
list_2 = list(c.items())
result:
[('AAW', [147, 124]), ('AAA', [123, 456])]
note that the converted data is probably better left as dictionary. Converting to list again loses the "key" feature of the dictionary.
On the other hand, if you want to retain the order of the "keys" of the original list of tuples, unless you're using python 3.6/3.7, you'd have to create a list with the original "keys" (ordered, unique), then rebuild the list from the dictionary. Or use an OrderedDict but then you cannot use defaultdict (or use a recipe)
Note that this answer would not necessarily retain the order of the original list, if that is a consideration.
â blhsing
1 hour ago
true, unless you're using python 3.7. To retain the original order you'd have to create a list with the original "keys" (ordered, unique), then rebuild the list from the dictionary.
â Jean-François Fabre
1 hour ago
add a comment |Â
up vote
3
down vote
You can use a dict to keep track of the indices of each key to keep the time complexity O(n):
list_2 =
i =
for k, s in list_1:
if k not in i:
list_2.append((k, s))
i[k] = len(i)
else:
list_2[i[k]][1].extend(s)
list_2 would become:
[('AAA', [123, 456]), ('AAW', [147, 124])]
add a comment |Â
up vote
2
down vote
You can create a dictionary and loop through the list. If the item present in dictionary append the value to already existing list else assign the value to key.
dict_1 =
for item in list1:
if item[0] in dict_1:
dict_1[item[0]].append(item[1][0])
else:
dict_1[item[0]] = item[1]
list_2 = list(dict_1.items())
New contributor
S.Harish is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |Â
up vote
1
down vote
Similarly to other answers, you can use a dictionary to associate each key with a list of values. This is implemented in the function merge_by_keys in the code snippet below.
import pprint
list_1 = [("AAA", [123]), ("AAA", [456]), ("AAW", [147]), ("AAW", [124])]
list_2 = [("AAA", [123, 456]), ("AAW", [147, 124])]
def merge_by_key(ts):
d =
for t in ts:
key = t[0]
values = t[1]
if key not in d:
d[key] = values[:]
else:
d[key].extend(values)
return d.items()
result = merge_by_key(list_1)
pprint.pprint(result)
add a comment |Â
up vote
0
down vote
from itertools import chain, groupby
from operator import itemgetter
list_2 = [(k, list(chain(*(x[1] for x in g))))
for k, g in groupby(list_1, itemgetter(0))]
Of if the lists always contain 1 element
list_2 = [(k, [x[1][0] for x in g])
for k, g in groupby(list_1, itemgetter(0))]
add a comment |Â
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
5
down vote
The most performant approach is to use a collections.defaultdict dictionary to store data as an expanding list, then convert back to tuple/list if needed:
import collections
list_1 = [("AAA", [123]), ("AAA", [456]), ("AAW", [147]), ("AAW", [124])]
c = collections.defaultdict(list)
for a,b in list_1:
c[a].extend(b) # add to existing list or create a new one
list_2 = list(c.items())
result:
[('AAW', [147, 124]), ('AAA', [123, 456])]
note that the converted data is probably better left as dictionary. Converting to list again loses the "key" feature of the dictionary.
On the other hand, if you want to retain the order of the "keys" of the original list of tuples, unless you're using python 3.6/3.7, you'd have to create a list with the original "keys" (ordered, unique), then rebuild the list from the dictionary. Or use an OrderedDict but then you cannot use defaultdict (or use a recipe)
Note that this answer would not necessarily retain the order of the original list, if that is a consideration.
â blhsing
1 hour ago
true, unless you're using python 3.7. To retain the original order you'd have to create a list with the original "keys" (ordered, unique), then rebuild the list from the dictionary.
â Jean-François Fabre
1 hour ago
add a comment |Â
up vote
5
down vote
The most performant approach is to use a collections.defaultdict dictionary to store data as an expanding list, then convert back to tuple/list if needed:
import collections
list_1 = [("AAA", [123]), ("AAA", [456]), ("AAW", [147]), ("AAW", [124])]
c = collections.defaultdict(list)
for a,b in list_1:
c[a].extend(b) # add to existing list or create a new one
list_2 = list(c.items())
result:
[('AAW', [147, 124]), ('AAA', [123, 456])]
note that the converted data is probably better left as dictionary. Converting to list again loses the "key" feature of the dictionary.
On the other hand, if you want to retain the order of the "keys" of the original list of tuples, unless you're using python 3.6/3.7, you'd have to create a list with the original "keys" (ordered, unique), then rebuild the list from the dictionary. Or use an OrderedDict but then you cannot use defaultdict (or use a recipe)
Note that this answer would not necessarily retain the order of the original list, if that is a consideration.
â blhsing
1 hour ago
true, unless you're using python 3.7. To retain the original order you'd have to create a list with the original "keys" (ordered, unique), then rebuild the list from the dictionary.
â Jean-François Fabre
1 hour ago
add a comment |Â
up vote
5
down vote
up vote
5
down vote
The most performant approach is to use a collections.defaultdict dictionary to store data as an expanding list, then convert back to tuple/list if needed:
import collections
list_1 = [("AAA", [123]), ("AAA", [456]), ("AAW", [147]), ("AAW", [124])]
c = collections.defaultdict(list)
for a,b in list_1:
c[a].extend(b) # add to existing list or create a new one
list_2 = list(c.items())
result:
[('AAW', [147, 124]), ('AAA', [123, 456])]
note that the converted data is probably better left as dictionary. Converting to list again loses the "key" feature of the dictionary.
On the other hand, if you want to retain the order of the "keys" of the original list of tuples, unless you're using python 3.6/3.7, you'd have to create a list with the original "keys" (ordered, unique), then rebuild the list from the dictionary. Or use an OrderedDict but then you cannot use defaultdict (or use a recipe)
The most performant approach is to use a collections.defaultdict dictionary to store data as an expanding list, then convert back to tuple/list if needed:
import collections
list_1 = [("AAA", [123]), ("AAA", [456]), ("AAW", [147]), ("AAW", [124])]
c = collections.defaultdict(list)
for a,b in list_1:
c[a].extend(b) # add to existing list or create a new one
list_2 = list(c.items())
result:
[('AAW', [147, 124]), ('AAA', [123, 456])]
note that the converted data is probably better left as dictionary. Converting to list again loses the "key" feature of the dictionary.
On the other hand, if you want to retain the order of the "keys" of the original list of tuples, unless you're using python 3.6/3.7, you'd have to create a list with the original "keys" (ordered, unique), then rebuild the list from the dictionary. Or use an OrderedDict but then you cannot use defaultdict (or use a recipe)
edited 1 hour ago
answered 1 hour ago
Jean-François Fabre
92.1k847102
92.1k847102
Note that this answer would not necessarily retain the order of the original list, if that is a consideration.
â blhsing
1 hour ago
true, unless you're using python 3.7. To retain the original order you'd have to create a list with the original "keys" (ordered, unique), then rebuild the list from the dictionary.
â Jean-François Fabre
1 hour ago
add a comment |Â
Note that this answer would not necessarily retain the order of the original list, if that is a consideration.
â blhsing
1 hour ago
true, unless you're using python 3.7. To retain the original order you'd have to create a list with the original "keys" (ordered, unique), then rebuild the list from the dictionary.
â Jean-François Fabre
1 hour ago
Note that this answer would not necessarily retain the order of the original list, if that is a consideration.
â blhsing
1 hour ago
Note that this answer would not necessarily retain the order of the original list, if that is a consideration.
â blhsing
1 hour ago
true, unless you're using python 3.7. To retain the original order you'd have to create a list with the original "keys" (ordered, unique), then rebuild the list from the dictionary.
â Jean-François Fabre
1 hour ago
true, unless you're using python 3.7. To retain the original order you'd have to create a list with the original "keys" (ordered, unique), then rebuild the list from the dictionary.
â Jean-François Fabre
1 hour ago
add a comment |Â
up vote
3
down vote
You can use a dict to keep track of the indices of each key to keep the time complexity O(n):
list_2 =
i =
for k, s in list_1:
if k not in i:
list_2.append((k, s))
i[k] = len(i)
else:
list_2[i[k]][1].extend(s)
list_2 would become:
[('AAA', [123, 456]), ('AAW', [147, 124])]
add a comment |Â
up vote
3
down vote
You can use a dict to keep track of the indices of each key to keep the time complexity O(n):
list_2 =
i =
for k, s in list_1:
if k not in i:
list_2.append((k, s))
i[k] = len(i)
else:
list_2[i[k]][1].extend(s)
list_2 would become:
[('AAA', [123, 456]), ('AAW', [147, 124])]
add a comment |Â
up vote
3
down vote
up vote
3
down vote
You can use a dict to keep track of the indices of each key to keep the time complexity O(n):
list_2 =
i =
for k, s in list_1:
if k not in i:
list_2.append((k, s))
i[k] = len(i)
else:
list_2[i[k]][1].extend(s)
list_2 would become:
[('AAA', [123, 456]), ('AAW', [147, 124])]
You can use a dict to keep track of the indices of each key to keep the time complexity O(n):
list_2 =
i =
for k, s in list_1:
if k not in i:
list_2.append((k, s))
i[k] = len(i)
else:
list_2[i[k]][1].extend(s)
list_2 would become:
[('AAA', [123, 456]), ('AAW', [147, 124])]
answered 1 hour ago
blhsing
16.4k2631
16.4k2631
add a comment |Â
add a comment |Â
up vote
2
down vote
You can create a dictionary and loop through the list. If the item present in dictionary append the value to already existing list else assign the value to key.
dict_1 =
for item in list1:
if item[0] in dict_1:
dict_1[item[0]].append(item[1][0])
else:
dict_1[item[0]] = item[1]
list_2 = list(dict_1.items())
New contributor
S.Harish is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |Â
up vote
2
down vote
You can create a dictionary and loop through the list. If the item present in dictionary append the value to already existing list else assign the value to key.
dict_1 =
for item in list1:
if item[0] in dict_1:
dict_1[item[0]].append(item[1][0])
else:
dict_1[item[0]] = item[1]
list_2 = list(dict_1.items())
New contributor
S.Harish is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |Â
up vote
2
down vote
up vote
2
down vote
You can create a dictionary and loop through the list. If the item present in dictionary append the value to already existing list else assign the value to key.
dict_1 =
for item in list1:
if item[0] in dict_1:
dict_1[item[0]].append(item[1][0])
else:
dict_1[item[0]] = item[1]
list_2 = list(dict_1.items())
New contributor
S.Harish is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
You can create a dictionary and loop through the list. If the item present in dictionary append the value to already existing list else assign the value to key.
dict_1 =
for item in list1:
if item[0] in dict_1:
dict_1[item[0]].append(item[1][0])
else:
dict_1[item[0]] = item[1]
list_2 = list(dict_1.items())
New contributor
S.Harish is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
edited 1 hour ago
Aran-Fey
20.2k52962
20.2k52962
New contributor
S.Harish is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
answered 1 hour ago
S.Harish
664
664
New contributor
S.Harish is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
S.Harish is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
S.Harish is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |Â
add a comment |Â
up vote
1
down vote
Similarly to other answers, you can use a dictionary to associate each key with a list of values. This is implemented in the function merge_by_keys in the code snippet below.
import pprint
list_1 = [("AAA", [123]), ("AAA", [456]), ("AAW", [147]), ("AAW", [124])]
list_2 = [("AAA", [123, 456]), ("AAW", [147, 124])]
def merge_by_key(ts):
d =
for t in ts:
key = t[0]
values = t[1]
if key not in d:
d[key] = values[:]
else:
d[key].extend(values)
return d.items()
result = merge_by_key(list_1)
pprint.pprint(result)
add a comment |Â
up vote
1
down vote
Similarly to other answers, you can use a dictionary to associate each key with a list of values. This is implemented in the function merge_by_keys in the code snippet below.
import pprint
list_1 = [("AAA", [123]), ("AAA", [456]), ("AAW", [147]), ("AAW", [124])]
list_2 = [("AAA", [123, 456]), ("AAW", [147, 124])]
def merge_by_key(ts):
d =
for t in ts:
key = t[0]
values = t[1]
if key not in d:
d[key] = values[:]
else:
d[key].extend(values)
return d.items()
result = merge_by_key(list_1)
pprint.pprint(result)
add a comment |Â
up vote
1
down vote
up vote
1
down vote
Similarly to other answers, you can use a dictionary to associate each key with a list of values. This is implemented in the function merge_by_keys in the code snippet below.
import pprint
list_1 = [("AAA", [123]), ("AAA", [456]), ("AAW", [147]), ("AAW", [124])]
list_2 = [("AAA", [123, 456]), ("AAW", [147, 124])]
def merge_by_key(ts):
d =
for t in ts:
key = t[0]
values = t[1]
if key not in d:
d[key] = values[:]
else:
d[key].extend(values)
return d.items()
result = merge_by_key(list_1)
pprint.pprint(result)
Similarly to other answers, you can use a dictionary to associate each key with a list of values. This is implemented in the function merge_by_keys in the code snippet below.
import pprint
list_1 = [("AAA", [123]), ("AAA", [456]), ("AAW", [147]), ("AAW", [124])]
list_2 = [("AAA", [123, 456]), ("AAW", [147, 124])]
def merge_by_key(ts):
d =
for t in ts:
key = t[0]
values = t[1]
if key not in d:
d[key] = values[:]
else:
d[key].extend(values)
return d.items()
result = merge_by_key(list_1)
pprint.pprint(result)
answered 1 hour ago
Odysseas
445210
445210
add a comment |Â
add a comment |Â
up vote
0
down vote
from itertools import chain, groupby
from operator import itemgetter
list_2 = [(k, list(chain(*(x[1] for x in g))))
for k, g in groupby(list_1, itemgetter(0))]
Of if the lists always contain 1 element
list_2 = [(k, [x[1][0] for x in g])
for k, g in groupby(list_1, itemgetter(0))]
add a comment |Â
up vote
0
down vote
from itertools import chain, groupby
from operator import itemgetter
list_2 = [(k, list(chain(*(x[1] for x in g))))
for k, g in groupby(list_1, itemgetter(0))]
Of if the lists always contain 1 element
list_2 = [(k, [x[1][0] for x in g])
for k, g in groupby(list_1, itemgetter(0))]
add a comment |Â
up vote
0
down vote
up vote
0
down vote
from itertools import chain, groupby
from operator import itemgetter
list_2 = [(k, list(chain(*(x[1] for x in g))))
for k, g in groupby(list_1, itemgetter(0))]
Of if the lists always contain 1 element
list_2 = [(k, [x[1][0] for x in g])
for k, g in groupby(list_1, itemgetter(0))]
from itertools import chain, groupby
from operator import itemgetter
list_2 = [(k, list(chain(*(x[1] for x in g))))
for k, g in groupby(list_1, itemgetter(0))]
Of if the lists always contain 1 element
list_2 = [(k, [x[1][0] for x in g])
for k, g in groupby(list_1, itemgetter(0))]
edited 1 hour ago
answered 1 hour ago
lightalchemist
6,07713148
6,07713148
add a comment |Â
add a comment |Â
Theprofessor14 is a new contributor. Be nice, and check out our Code of Conduct.
Theprofessor14 is a new contributor. Be nice, and check out our Code of Conduct.
Theprofessor14 is a new contributor. Be nice, and check out our Code of Conduct.
Theprofessor14 is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52454582%2fmerge-a-a-tuple-with-the-same-key%23new-answer', 'question_page');
);
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password

1
Related: Python: merge lists of tuples based on its values
â Aran-Fey
1 hour ago
1
all those years and not a single exact dupe... I had a good look. Maybe it's somewhere, well...
â Jean-François Fabre
1 hour ago