Reputation: 338
So, I have a list of lists in the following manner.
ab_list = [['AB','35'],['AB','78'],['CD','98'],['CD','41'],['CD','67'].....]
Now, I want to convert this list into a dictionary such that it has the following form:
ab_dict = {'AB':'35|78','CD':'98|41|67'.........}
So, if the second element of the list is repeated it should be joined by pipeline and that will become the value. I am not getting the logic of how to do this. The code I am trying is:
for val in ab_list:
for value in final_list:
if val[0] == value[0]:
value[1] = value[1] + "|" + val[1]
But this is not working properly. How to do this?
Upvotes: 1
Views: 92
Reputation: 5965
ab_list = [['AB', '35'], ['AB', '78'], ['CD', '98'], ['CD', '41'], ['CD', '67']]
ab_dict = {}
for k, v in ab_list:
if k in ab_dict:
ab_dict[k] += '|' + v
else:
ab_dict[k] = v
print(ab_dict)
Output:
{'AB': '35|78', 'CD': '98|41|67'}
Upvotes: 3
Reputation: 1238
Try this one:
# Stage-1
#
lst = [['AB', '35'], ['AB', '78'], ['CD', '98']]
tmp = []
for i in lst:
tmp.append(i[0])
tmp = list(set(tmp))
# Stage-2
#
dct = {}
for i in tmp:
dct.update({i: []})
for i in lst:
dct[i[0]].append(i[1])
# Stage-3
#
final = {}
for i, j in dct.items():
string = ''
if len(j) == 1:
string = j[0]
else:
for k in j:
string += k + ' | '
string = string[:-3]
final.update({i: string})
Result:
{'AB': '35 | 78', 'CD': '98'}
Upvotes: 1
Reputation: 59701
EDIT: The solution below only works if all pairs with the same first element are consecutive, which is the case in the example but may not be in general (otherwise you would need to sort the list first to make it work, which would not be a very good solution).
This is one way to do it with groupby
:
from itertools import groupby
ab_list = [['AB', '35'], ['AB', '78'], ['CD', '98'], ['CD', '41'], ['CD', '67']]
ab_dict = {k: '|'.join(it[1] for it in v) for k, v in groupby(ab_list, lambda it: it[0])}
print(ab_dict)
# {'AB': '35|78', 'CD': '98|41|67'}
Upvotes: 1
Reputation: 82765
This is one approach using setdefault
and a simple iteration.
Ex:
ab_list = [['AB','35'],['AB','78'],['CD','98'],['CD','41'],['CD','67']]
result = {}
for k, v in ab_list:
result.setdefault(k, []).append(v)
ab_dict = {k: "|".join(v) for k, v in result.items()}
print(ab_dict)
Output:
{'AB': '35|78', 'CD': '98|41|67'}
Upvotes: 6