【问题标题】:Iterate over list of file names to see if file name is in dictionary Values (Valuse are lists), then print Key and file name遍历文件名列表以查看文件名是否在字典值中(值是列表),然后打印键和文件名
【发布时间】:2020-10-01 14:30:36
【问题描述】:

我仅限于使用 python 2.7 来完成这项工作。

我想遍历 file_list 以查找哪些文件名包含任何 dict 值列表。 然后打印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']

这是我在工作中自愿参与的一个项目,我是 python 新手。 真正让我困惑的是字典key:values 作为一个列表。

非常感谢任何帮助:-)

【问题讨论】:

    标签: python list python-2.7 dictionary


    【解决方案1】:
    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
    

    【讨论】:

    • 阿明 - 感谢您的帮助和快速响应,非常感谢您的帮助 - 凯西
    猜你喜欢
    • 2013-11-24
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 2013-11-30
    • 2019-07-19
    • 2016-02-26
    • 1970-01-01
    • 2016-12-17
    相关资源
    最近更新 更多