I am trying to enter the values in a list into an empty dictionary but I keep getting error messages and I don't know what I did wrong.
My list lst
looks like this:
[[123,456],
[123,123],
[123,567],
[234,344],
[234,345],
[234,988]...]
I was asked to first create an empty dictionary that contains the first number from lst
(should look like this 123:[],234:[]
), then enter the second number that follows the first number in the list into the dictionary and the dictionary should look something like {123:[456,567],234:[344,345,988]...}
(if the first number equals to the second number, the second number should not be included)
I created an empty dictionary and then print the dictionary values for the numbers using the following code:
dic = dict((i, []) for i in lst)
for key, value in dic.items():
if key in lst:
print(key, ":", value)
When I tried to put the values from lst
into the dictionary using the following code:
for w in lst:
if w[0] in dic.keys() and w[0] != w[1]:
dic[w[0]].append(w[1])
lst2 = []
for a in lst[0:10]:
lst2.append(dic[a])
print(lst2)
I got an error message below:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-135-610d94e48548> in <module>
8
9 for w in idList:
---> 10 if w[0] in dic.keys() and w[0] != w[1]:
11 dic[w[0]].append(w[1])
12
TypeError: 'int' object is not subscriptable
Does anyone know what happened there and how can I solve this?
Many Thanks!