【问题标题】:Print each dictionary from a list in a new line in a string在字符串的新行中打印列表中的每个字典
【发布时间】:2021-07-02 11:46:11
【问题描述】:

我有一个字符串和一个字典列表:

body = "Next, we wil give you detailed information about each case: %s"

feature_list = [{'FEATURE_NAME': 'FT02', 'Number of users who tested it ': 30, 'Number of problems detected' : 2},
{'FEATURE_NAME': 'SW045', 'Number of users who tested it ': 5, 'Number of problems detected' : 0}
{'FEATURE_NAME': 'SW04',  'Number of users who tested it ': 23, 'Number of problems detected' : 8}]

我想创建一个这样的新字符串:

newbody = """
    Next, we wil give you detailed information about each case :
    {'FEATURE_NAME': 'FT02', 'Number of users who tested it ': 30, 'Number of problems detected' : 2}
    {'FEATURE_NAME': 'SW045', 'Number of users who tested it ': 5, 'Number of problems detected' : 0}
    {'FEATURE_NAME': 'SW049',  'Number of users who tested it ': 23, 'Number of problems detected' : 8}]
    """

我试图遍历列表,但这样我只能得到字符串中的最后一个字典。我知道可以按原样给出列表,但这看起来非常丑陋且难以阅读。

【问题讨论】:

  • 你能告诉我们你是如何尝试迭代的,以及你得到了什么,与你“想要”得到的相比吗?

标签: python string dictionary


【解决方案1】:

加入feature_list中的项目,然后打印

body = "Next, we wil give you detailed information about each case:"

feature_list = [{'FEATURE_NAME': 'FT02', 'Number of users who tested it ': 30, 'Number of problems detected' : 2},
{'FEATURE_NAME': 'SW045', 'Number of users who tested it ': 5, 'Number of problems detected' : 0},
{'FEATURE_NAME': 'SW04',  'Number of users who tested it ': 23, 'Number of problems detected' : 8}]
features = '\n'.join(str(feature) for feature in feature_list)
print(f'{body}\n{features}')

注意,制作一个漂亮的字符串而不是显示字典会好得多。

【讨论】:

    猜你喜欢
    • 2013-06-16
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 2016-10-29
    • 2020-04-09
    • 2021-02-24
    相关资源
    最近更新 更多