Vinay Naik
Vinay Naik

Reputation: 31

2D Array to Dictionary conversion

How to convert Input to Output ?

Input : mat=[[3, 37],[1, 41],[2, 37],[5, 41],[4, 35]]

Output: mat={37:[3,2],41:[1,5],35:[4]}

I have tried below code :

dic={}
x=[]
for i in mat:
    dic[i[1]]=list()
    dic[i[1]]=i[0]

Got This answer : {37: 2, 41: 5, 35: 4}

Upvotes: 1

Views: 69

Answers (5)

nour aldin nasany
nour aldin nasany

Reputation: 1

try this:

dic={}
for i in mat:
    if dic.has_key(i[1]):
         dic[i[1]].append(i[0])
    else:
        dic[i[1]]=list()
        dic[i[1]].append(i[0])

Upvotes: 0

Ilya
Ilya

Reputation: 802

Using defaultdict is a good practice when a default value is needed.

from collections import defaultdict

m = defaultdict(list)
for val, key in mat:
    m[key].append(val)

Upvotes: 1

Dima Chubarov
Dima Chubarov

Reputation: 17179

You are almost there. The setdefault()/append() solution already works perfectly. An alternative would be to use the list + operator that concatenates two lists and returns the result:

dic = {}
for i,j in mat:
    dic[j] = dic.get(j, []) + [i]

Upvotes: 0

user16004728
user16004728

Reputation:

Try this:

dic={}
for i in mat:
    if i[1] not in dic:
        dic[i[1]] = []
    dic[i[1]].append(i[0])

Upvotes: 0

dumbPotato21
dumbPotato21

Reputation: 5715

You could use setdefault

d = {}
for a,b in mat:
    d.setdefault(b, []).append(a)

Upvotes: 1

Related Questions