0

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!

tyc_8991
  • 37
  • 1
  • 9

3 Answers3

0

Most close to your solution:

dic = {i[0]: [] for i in lst}

for w in lst:
    if w[0] != w[1] 
        dic[w[0]].append(w[1])

Note. To do the first step more fancy you can use defaultdict and groupby for second How do I use Python's itertools.groupby()?

Serge
  • 3,387
  • 3
  • 16
  • 34
0
l = [[123,456],
[123,123],
[123,567],
[234,344],
[234,345],
[234,988]]

dic = {} #empty dictionary

# creating dictionary with inner list first element as key and value as list
for i in l:
    dic.update({i[0]:[]})

# adding the second value to the corresponding key in list
for i in l:
    dic[i[0]].append(i[1])


print(dic)

output

{123: [456, 123, 567], 234: [344, 345, 988]}
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
0
lst = [[123,456],[123,123],[123,567],[234,344],[234,345],[234,988]]

dic = dict((i[0], []) for i in lst)

for i in lst:
   if i[0] != i[1]:
       dic[i[0]].append(i[1])
kartheek
  • 690
  • 6
  • 9