python - 将字典列表值放在文本文件模板中
问题描述
{'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)
解决方案
您希望将替换字典转换为仅包含每个操作中相关的值。您可以通过为每个索引创建一个生成器来做到这一点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 '}
推荐阅读
- django - 未调用 Django Channels WebSocketConsumer 的 Disconnect() 方法
- python - 我无法理解“numpy.ndarray.dot”官方文档的详细信息
- html - 从另一个页面导航到页面的特定部分不起作用
- python - 为什么在拟合和预测模型时密集层 input_shapes 存在差异?
- r - 在 Alluvial 中进行的类似可视化
- c++ - 是否可以为零模板参数进行模板特化?
- angular - VSCode 打字稿自动导入
- python - txt 到 tfrecords 的转换
- c++ - 如何获取系统序列号?
- laravel - Laravel 中的登录系统向我显示这些凭据与我们的记录不匹配