Reputation: 31
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
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
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
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
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
Reputation: 5715
You could use setdefault
d = {}
for a,b in mat:
d.setdefault(b, []).append(a)
Upvotes: 1