将Python字典组合成字符串

2024-09-29 02:16:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我这里有一本字典:

dict = {'AB': 1, 'AE': '0', 'CC': '3'}

我正试图将字典转换成精确的字符串格式:

AB1,AE0,CC3

我目前正在尝试:

string = ",".join(("{},{}".format(*i) for i in dict.items()))

但我的成果是:

AB,1,AE,0,CC,3

只差一点点。你知道吗

有人知道如何将这本词典正确地格式化成字符串吗?你知道吗

谢谢


Tags: 字符串formatforstring字典ab格式dict
3条回答

代码:

dict = {'AB': 1, 'AE': '0', 'CC': '3'}
string=','.join([i+str(dict[i]) for i in dict])
print(string)

输出:

AB1,AE0,CC3

好了(删除逗号):

d = {'AB': 1, 'AE': '0', 'CC': '3'}

output = ",".join(["{}{}".format(key, value) for key, value in d.items()])
#                   ^^^^
print(output)

这就产生了

AB1,AE0,CC3

或者使用原始的拆包方法:

output = ",".join(["{}{}".format(*x) for x in d.items()])

另外,请不要以内置对象(dict、list、tuple等)命名变量。你知道吗

如果您使用的是Python 3,则可以使用所谓的f字符串:

d = {'AB': 1, 'AE': '0', 'CC': '3'}
out = ','.join([f'{i}{d[i]}' for i in d.keys()])
print(out)

输出:

AB1,AE0,CC3

如果您想了解更多关于f字符串的信息,请参见tutorial。请记住,此解决方案仅适用于Python3.3及更新版本。你知道吗

相关问题 更多 >