Python 如何从列表中字典的字符串值中删除字符?

Python 如何从列表中字典的字符串值中删除字符?,python,dictionary,Python,Dictionary,如何仅在这些'\n'存在时删除它们(我不知道如何检查),并返回仅由“从字典'\n'清除”的值组成的列表?谢谢:) 您可以重复使用dict.items()和strip值来删除回车符,然后使用列表理解对每个dict with open("name.txt") as file: for l in file: listofdict.append(dict(zip(['name','surname','age']), l.split('|')))) return listofdic

如何仅在这些'\n'存在时删除它们(我不知道如何检查),并返回仅由“从字典'\n'清除”的值组成的列表?谢谢:)


您可以重复使用
dict.items()
strip
值来删除回车符,然后使用列表理解对每个
dict

with open("name.txt") as file:
    for l in file:
        listofdict.append(dict(zip(['name','surname','age']), l.split('|'))))
return listofdict
很难说没有看到您的文件,但是您可以通过调整您的文件读取而不进行任何后处理

>>> [{key: val.strip() for key, val in i.items()} for i in listofdict]
[{'surname': 'Mikeson', 'age': '15', 'name': 'Mike'},
 {'surname': 'Johnson', 'age': '15', 'name': 'John'},
 {'surname': 'Tomson', 'age': '19', 'name': 'Tomy'}]

您的预期输出是什么?非常感谢您的帮助!@HansJohanbach如果这回答了您的问题,您可以选择左侧的绿色复选标记:)哦,我当然会的,但是它需要经过3分钟:)
>>> [{key: val.strip() for key, val in i.items()} for i in listofdict]
[{'surname': 'Mikeson', 'age': '15', 'name': 'Mike'},
 {'surname': 'Johnson', 'age': '15', 'name': 'John'},
 {'surname': 'Tomson', 'age': '19', 'name': 'Tomy'}]
with open("name.txt") as file:
    listofdict = [dict(zip(['name','surname','age']), l.strip().split('|')) for l in file]
    return listofdict