gpt4 book ai didi

python - 如何替换字典值中的字符串

转载 作者:行者123 更新时间:2023-12-04 08:14:19 26 4
gpt4 key购买 nike

我的 parent 字典在下面

d = 
[{"code":1, "description":"This is only one %s", "name":"Hello"},
"code":2, "description":"This %s has one more %s", "name":"World"}]
我的输入 {'code':1, 'details':['A']}预计出 {"description":"This is only one A", "name":"Hello"}我的输入 {'code':2, 'details':['A','B']}预计出 {"description":"This A has one more B", "name":"World"}
  • %s在说明中
  • 它必须替换为 details 中的值 key
  • 最佳答案

    如果您通过您的 values作为对象元组,您可以使用 %s和字符串格式。

    d=[{"code":1, "description":"This is only one %s", "name":"Hello"},
    {"code":2, "description":"This %s has one more %s", "name":"World"}]

    def replace(code, values):
    for row in d:
    if row.get('code', None) == code:
    return {
    'description': row['description'] % (values),
    'name': row['name'],
    }
    return 'Code not Found'

    >>> replace(1, ('A'))
    {'description': 'This is only one A', 'name': 'Hello'}
    >>> replace(2, ('A', 'B'))
    {'description': 'This A has one more B', 'name': 'World'}
    >>>

    关于python - 如何替换字典值中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65785326/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com