convert 2D list to dict where duplicate values to keys and rest of values to list

Question:

As No import any library To Do This

x=[['A',1],['B',2],['C',3]]
y=[['A',100],['B',200],['C',300]]
z=[['A',1000],['B',2000],['C',3000]]

output must:
{'A':[1,100,1000],'B':[2,200,2000],'C':[3,300,3000]}

I tried :

dic=dict(filter(lambda i:i[0]==i[0],[x,y,z]))

So As Data I need first duplicated value to key , and common values to this key as list

Asked By: hani128

||

Answers:

Try:

x = [["A", 1], ["B", 2], ["C", 3]]
y = [["A", 100], ["B", 200], ["C", 300]]
z = [["A", 1000], ["B", 2000], ["C", 3000]]

out = {}
for l in (x, y, z):
    for a, b in l:
        out.setdefault(a, []).append(b)

print(out)

Prints:

{"A": [1, 100, 1000], "B": [2, 200, 2000], "C": [3, 300, 3000]}

EDIT: Without dict.setdefault:

x = [["A", 1], ["B", 2], ["C", 3]]
y = [["A", 100], ["B", 200], ["C", 300]]
z = [["A", 1000], ["B", 2000], ["C", 3000]]

out = {}
for l in (x, y, z):
    for a, b in l:
        if a in out:
            out[a].append(b)
        else:
            out[a] = [b]

print(out)
Answered By: Andrej Kesely

You can use zip to merge the lists to a list of tuples and insert them to a dict with setdefault

d = dict()
for k, v in zip(*zip(*x, *y, *z)):
    d.setdefault(k, []).append(v)

print(d) # {'A': [1, 100, 1000], 'B': [2, 200, 2000], 'C': [3, 300, 3000]}
Answered By: Guy

Let’s use a dictionary comprehension:

dic_={x[0]: [x[1], y[1],z[1]] for (x,y,z) in zip(x, y,z)}

Output

>>> dic
>>> {'A': [1, 100, 1000], 'B': [2, 200, 2000], 'C': [3, 300, 3000]}
Answered By: Khaled DELLAL
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.