首页 > 解决方案 > 将字典列表值放在文本文件模板中

问题描述

{'test_name': ['D S', 'C S'],
 'date': ['23/04/2021', '02/05/2021'],
 'link1': ['smk.com', 'xyz.com '],
 'link2': ['pst.com', 'abc.com ']}

从字典中,需要在模板文件中插入值。

(模板文件)file.txt

Pending of taking test {test_name} was due on {date}. Follow the below link
X_link : {link1} --> replace with xyz from one.txt

y_link : {link2} --> replace with abc from one.txt

预期输出:

在迭代 1 中:

Pending of taking test D S was due on 23/04/2021. Follow the below link
X_link : smk.com

y_link : pst.com

在迭代 2 中:

Pending of taking test c S was due on 02/05/2021. Follow the below link
X_link : xyz.com

y_link : abc.com

尝试实施但无法按预期打印

        requirements = {}
        for req in reqs:
            list_values = [x for x in reqs[req]]
            print(list_values)
            for val in list_values:
                print(val)
                requirements.update( {reqs : val} )
        with open(r'file.txt') as file2:
                m = ''
                for line in file2:
                    m+=line.format(**requirements)
                    print(m)

标签: pythonpython-3.xdictionary

解决方案


您希望将替换字典转换为仅包含每个操作中相关的值。您可以通过为每个索引创建一个生成器来做到这一点i,这将为原始替换字典中的每个项目创建一个新字典{key: val[i]}。像这样:

replacements = { <your dict> }

iterations = 2  # However many values you have in each list
for current_replacements in ({key: val[i] for key, val in replacements.items()}
                             for i in range(iterations)):
  formatted = template_string.format(**current_replacements)
  # do something with formatted output

在 for 循环中,迭代current_replacements将具有值:

  • {'test_name': 'D S', 'date': '23/04/2021', 'link1': 'smk.com', 'link2': 'pst.com'}
  • {'test_name': 'C S', 'date': '02/05/2021', 'link1': 'xyz.com ', 'link2': 'abc.com '}

推荐阅读