字典python 3的字符串格式

万万

我有一本字典,我想以字符串格式打印它的键和值:

示例 1:

dic = {'A': 1, 'B': 2}
Output: "This is output A:1 B:2"

示例 2:

dic = {'A': 1, 'B': 2, 'C': 3}
Output: "This is output A:1 B:2 C:3"

当我有更多钥匙时,我想要一般的答案。谢谢你。

黑乌鸦

您可以遍历键值对,并相应地打印输出:

dic = {'A': 1, 'B': 2, 'C': 3}
print('This is output', end=' ')
for k,v in dic.items():
    print(str(k) + ':' + str(v), end=' ')

输出

This is output A:1 B:2 C:3 

或者,您可以连接字符串(相同的输出):

dic = {'A': 1, 'B': 2, 'C': 3}
s = ''
for k,v in dic.items():
    s += f'{k}:{v} '   #thanks to @blueteeth
print('This is output', s.strip())

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章