Search code examples
pythonintliteralsradix

Value Error cannot index


text_file = ['Cats','Dogs','Frogs','(pass)', 'ants']
final_l = [[1], [2], [3], [5]]
final_dict = {'Dogs': [1], 'Cats': [1], 'Frogs': [1], 'ants': [1]}

for k, v in final_dict.items():
    for sl in final_l:
        for num in sl:
            if text_file[int(num)] == k:
                sl.append(k)
                sl.append(v)
print(final_l)

Traceback (most recent call last):
  File "/Users/Luan/Desktop/1.py", line 9, in <module>
    if text_file[int(num)] == k:
ValueError: invalid literal for int() with base 10: 'Frogs'

So confused. Where is going wrong??? Why does it keep giving me this Value Error?? Why cannot I index? I want to put it like this:

final_l = [[1, "Cats", [1]], [2, "Dogs", [1]], [3, "Frogs", [1]], [5, "ants", [1]]]

Solution

  • The main issue here is you are iterating through a list while appending to it new values which will cause you errors and because also you happened to use the values you append to this list sl who are not right for indexing (like 'Frogs'), so my obvious suggestion would be to create a new list for that:

    >>> new = []
    >>> for k,v in final_dict.items():
        for i,sl in enumerate(final_l):
            for num in sl:
                if text_file[num-1] == k:
                    new.append(sl+[k,v])
    
    
    >>> new
    [[3, 'Frogs', [1]], [5, 'ants', [1]], [2, 'Dogs', [1]], [1, 'Cats', [1]]]
    

    Please note, that list indexing starts from 0.