Skip to main content
 首页 » 编程设计

python之操作和打印 python 字典中的项目

2025年05月04日12mfryf

我有以下代码:

ex_dict={1:"how",3:"do you",7:"dotoday"} 
for key in ex_dict: 
    string= key," and this is ", ex_dict[key] 
    print (string) 

输出是:

(1, ' and this is ', 'how') 
(3, ' and this is ', 'do you') 
(7, ' and this is ', 'dotoday') 

我的预期输出:

1 and this is how 
3 and this is do you 
7 and this is dotoday 

我似乎无法弄清楚如何摆脱输出中的字典格式。

请您参考如下方法:

只需使用+ 来组合字符串:

string = str(key) + " and this is " + ex_dict[key] 

由于 key 是一个整数,而您只能使用 + 运算符连接字符串,因此您也应该将 key 转换为字符串。