Search code examples
pythonlistdictionarynlp

Getting the correct list values in a python dictionary


I would like my dictionary to have the values of the file name 'hello.txt' instead of the numerical value 1. My code is

file_list = [hello.txt, bye.txt, test.txt]
file_contents = ['text of hello', 'text of bye', 'text of test']
dict = {}
for i in range(len(file_list)):
    check = file_contents[i].lower()
    for item in words:
  
        if item in check:
            if item not in dict:
                dict[item] = []
  
            if item in dict:
                dict[item].append(i+1)

dict = {k: list(set(v)) for k, v in dict.items()}
print(dict)

The output I am currently getting is

{'test': [3], 'text': [1, 2, 3]}

But I would like it to be

{'test': [test.txt], 'text': [hello.txt, bye.txt, test.txt]}

How would I change this?


Solution

  • Instead of appending i + 1 to your dictionary, you can append the file name, i.e. file_list[i]

    dict[item].append(file_list[i])
    

    Note that you might have an error because your file names are not surrounded by quotes and are not considered as strings. Use this instead:

    file_list = ['hello.txt', 'bye.txt', 'test.txt']