有没有更好的方法将 dict 转换为由逗号分隔的字符串?

mar*_*lon 1 python

例如:

d = {'a':'1', 'b':'2', 'c':'3'}
Run Code Online (Sandbox Code Playgroud)

我想将 ds 作为 str 获取:

ds = 'a:1, b:2, c:3'
Run Code Online (Sandbox Code Playgroud)

我的转换功能:

 def convert_dict(my_dict):
        converted = ''
        for key, value in my_dict.items():
            converted += key + ':' + value + '?'
        return converted[0:-1]
Run Code Online (Sandbox Code Playgroud)

我怀疑应该有更好更简单的方法来做到这一点。

Sil*_*olo 5

你的做法没有任何问题。我们可以用推导式来让它更短一些。但是您的代码完全可以按原样理解,无需为此感到羞耻。

def convert_dict(my_dict):
  return ', '.join(f"{key}:{value}" for key, value in my_dict.items())
Run Code Online (Sandbox Code Playgroud)

如果您使用的 Python 版本早于 3.5,则需要使用.format而不是f""我在上面的示例中使用的字符串语法。