0

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])
Codcz
  • 13
  • 4

4 Answers4

1

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.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
0

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)
mhhabib
  • 2,975
  • 1
  • 15
  • 29
0

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
Aplet123
  • 33,825
  • 1
  • 29
  • 55
0

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]})
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50