[英]Iterate over list of file names to see if file name is in dictionary Values (Valuse are lists), then print Key and file name
I'm limited to using python 2.7 for this work.我仅限于使用 python 2.7 来完成这项工作。
I'd like to iterate over the file_list
looking for which file names contain any of the dict values lists.我想遍历
file_list
以查找哪些文件名包含任何 dict 值列表。 Then print the dict key and the file name.然后打印dict键和文件名。
## dictionary derived from opening and reading csv file
name_dict = {'kat': ['1', '2', '4'], 'rod': ['3', '7', '9'], 'tim': ['5', '6', '8']}
## list of files in a directory
file_list = ['1.pdf', '2.pdf', '3.pdf', '4.pdf', '5.pdf', '6.pdf', '7.pdf', '8.pdf', '9.pdf']
This is for a project I volunteered for at work and I'm new-ish to python.这是我在工作中自愿参与的一个项目,我对 python 很陌生。 It is the dictionary
key:values
as a list that is really confusing me.真正让我困惑的是字典
key:values
作为一个列表。
Any help is much appreciated:-)任何帮助深表感谢:-)
file_list = ['1.pdf', '2.pdf', '3.pdf', '4.pdf', '5.pdf', '6.pdf', '7.pdf', '8.pdf', '9.pdf']
name_dict = {'kat': ['1', '2', '4'], 'rod': ['3', '7', '9'], 'tim': ['5', '6', '8']}
for file in file_list:
file_no_ext = '.'.join(file.split('.')[:-1])
for key, value in name_dict.items():
if file_no_ext in value:
print(f'{file}: {key}')
break
and output:和 output:
1.pdf: kat
2.pdf: kat
3.pdf: rod
4.pdf: kat
5.pdf: tim
6.pdf: tim
7.pdf: rod
8.pdf: tim
9.pdf: rod
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.