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

Time:11-22

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

CodePudding user response:

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)

CodePudding user response:

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]}

CodePudding user response:

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]}
  • Related