在 python 字典中获取正确的列表值
Getting the correct list values in a python dictionary
我希望我的字典具有文件名的值 'hello.txt' 而不是数值 1。我的代码是
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)
我目前得到的输出是
{'test': [3], 'text': [1, 2, 3]}
但我希望它是
{'test': [test.txt], 'text': [hello.txt, bye.txt, test.txt]}
我该如何更改?
您可以附加文件名,而不是将 i + 1 附加到您的字典,即 file_list[i]
dict[item].append(file_list[i])
请注意,您可能会遇到错误,因为您的文件名没有被引号括起来并且不被视为字符串。改用这个:
file_list = ['hello.txt', 'bye.txt', 'test.txt']
我希望我的字典具有文件名的值 'hello.txt' 而不是数值 1。我的代码是
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)
我目前得到的输出是
{'test': [3], 'text': [1, 2, 3]}
但我希望它是
{'test': [test.txt], 'text': [hello.txt, bye.txt, test.txt]}
我该如何更改?
您可以附加文件名,而不是将 i + 1 附加到您的字典,即 file_list[i]
dict[item].append(file_list[i])
请注意,您可能会遇到错误,因为您的文件名没有被引号括起来并且不被视为字符串。改用这个:
file_list = ['hello.txt', 'bye.txt', 'test.txt']