You can do two dicts groupings with the first:
list_a = ['abc|1','bcd|2','cde|3'] list_b = ['1234|1','2345|2','3456|2','4567|2','5678|3'] d = defaultdict(list) from itertools import chain for k in chain(list_a,list_b): d[k.rsplit("|",1)[1]].append(k) print(d) print({v[0]:v[1:] for v in d.values()}) defaultdict(<type 'list'>, {'1': ['abc|1', '1234|1'], '3': ['cde|3', '5678|3'], '2': ['bcd|2', '2345|2', '3456|2', '4567|2']}) {'abc|1': ['1234|1'], 'cde|3': ['5678|3'], 'bcd|2': ['2345|2', '3456|2', '4567|2']}
You can avoid the list for single values ββby first checking the length if necessary.
d = {v[0]: (v[1:] if len(v)> 2 else v[-1]) for v in d.values()} print(d) {'abc|1': '1234|1', 'cde|3': '5678|3', 'bcd|2': ['2345|2', '3456|2', '4567|2']}
Using python3, the syntax is slightly better using extended iterative unpacking :
d = {k: (val if len(val) > 1 else val[0]) for k,*val in d.values()} print(d)
If you need an order based on the keys in the list, you will need OrderedDict:
list_a = ['abc|1', 'bcd|2', 'cde|3'] list_b = ['1234|1', '2345|2', '3456|2', '4567|2', '5678|3'] from collections import OrderedDict from itertools import chain od = OrderedDict() for k in chain(list_a, list_b): od.setdefault(k.rsplit("|",1)[1], []).append(k) d = OrderedDict((k, (val)) for k, *val in od.values())