我试图重命名一些键,并将分组键的值分组。我的内容如下:
text_image_old = {10_pdf 10_pdf0: "some text", 10_pdf 10_pdf1: "more text", 10_pdf 10_pdf2: "even more text"}使用regex,我可以迭代地替换名称,这样只留下10_pdf,但是由于循环,文本将只包含“更多的文本”(例如最后的值):
text_image_new = {re.sub('[a-zA-Z0-9_]+.pdf[0-9]', '', k): v for k, v in text_image_old.items()} 如何替换密钥并对值进行分组?谢谢!
编辑:预期的输出应该如下所示
text_image_new = {10_pdf :"some text" "more text" "even more text"}或者如果更容易得到:
text_image_new = {10_pdf :"some text more text even more text"}发布于 2018-11-15 16:30:45
我希望这对你有用,或者至少能帮你解决问题:
text_image_old = {'10_pdf 10_pdf0': "some text", '10_pdf 10_pdf1': "more text",\
'10_pdf 10_pdf2': "even more text"}
new_dict = {}
for k, v in text_image_old.items():
k = k.split(' ')[0]
if k in new_dict:
new_dict[k] += v + ' '
else:
new_dict[k] = v + ' '
print(new_dict)https://stackoverflow.com/questions/53322138
复制相似问题