遍历文件名列表以查看文件名是否在字典值

遍历文件名列表以查看文件名是否在字典值

本文介绍了遍历文件名列表以查看文件名是否在字典值(值是列表)中,然后打印键和文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仅限于使用python 2.7进行这项工作.

I'm limited to using python 2.7 for this work.

我想遍历file_list以查找哪些文件名包含任何dict值列表.然后打印dict键和文件名.

I'd like to iterate over the file_list looking for which file names contain any of the dict values lists.Then print the dict key and the file name.

## 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']

这是我自愿参加的一个项目,我对python很陌生.字典key:values作为列表确实使我感到困惑.

This is for a project I volunteered for at work and I'm new-ish to python.It is the dictionary key:values as a list that is really confusing me.

非常感谢您的帮助:-)

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

并输出:

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

这篇关于遍历文件名列表以查看文件名是否在字典值(值是列表)中,然后打印键和文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 19:17