Reputation: 13
I have list like this myList = [[5, 1], [6, 1], [7, 1], [8, 1], [9, 1], [10, 1]]
and I want to convert it to dict like {1:[5,6,7,8,9,10]}
the key is second argument of inner list.
I tried below code but it not work.
for i in range(len(myList))
myDic[myList[i][1]] = [myList[i][1]]
myDic[myList[i][1]].append(myList[i][0])
Upvotes: 0
Views: 87
Reputation: 46849
this can easily be done with a defaultdict
:
from collections import defaultdict
ret = defaultdict(list)
myList = [[5, 1], [6, 1], [7, 1], [8, 1], [9, 1], [10, 1]]
for value, key in myList:
ret[key].append(value)
print(ret) # defaultdict(<class 'list'>, {1: [5, 6, 7, 8, 9, 10]})
if you want to avoid defaultdict
, setdefault
helps:
ret = {}
myList = [[5, 1], [6, 1], [7, 1], [8, 1], [9, 1], [10, 1]]
for value, key in myList:
ret.setdefault(key, []).append(value)
print(ret)
note that defaultdict
is in the standard library; so if you use a reasonably modern python interpreter (with python 3 you are good anyway) you can use a defaultdict
.
Upvotes: 1
Reputation: 24232
You can do that easily with a defaultdict
:
myList = [[5, 1], [6, 1], [7, 1], [8, 1], [9, 1], [10, 1], [11, 2], [12, 2]]
from collections import defaultdict
out = defaultdict(list)
for val, key in myList:
out[key].append(val)
print(out)
# defaultdict(<class 'list'>, {1: [5, 6, 7, 8, 9, 10], 2: [11, 12]})
Upvotes: 0
Reputation: 35512
Use a defaultdict:
from collections import defaultdict
myDic = defaultdict(list) # values default to empty list
for a, b in myList:
myDic[b].append(a)
myDic = dict(myDic) # get rid of default value
Upvotes: 0
Reputation: 3121
Declared d
as the dictionary. Then append the first value into the dictionary using the second value as a key in 2D list.
myList = [[5, 1], [6, 1], [7, 1], [8, 1], [9, 1], [10, 1]]
d = {}
for elem in myList:
try:
d[elem[1]].append(elem[0])
except KeyError:
d[elem[1]] = [elem[0]]
print(d)
Upvotes: 0