在python字典中操作和打印项目

时间:2015-09-04 21:05:36

标签: python python-2.7

我有以下代码:

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

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

5 个答案:

答案 0 :(得分:5)

只需使用+组合字符串:

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

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

答案 1 :(得分:3)

您不会查看字典格式,而是查看tuples

  

在Python中,多元素元组看起来像:

     

1,2,3

     

基本元素是元组的每个元素之间的逗号。可以使用尾随逗号来编写多元素元组,例如

     

1,2,3,

     

但是尾随的逗号是完全可选的。就像Python中的所有其他表达式一样,多元素元组可以括在括号中,例如

     

(1,2,3)

     

     

(1,2,3,)

改为使用字符串格式:

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

此外:您可以使用

简化代码
ex_dict={1:"how",3:"do you",7:"dotoday"}
for key, val in ex_dict.iteritems(): #ex_dict.items() in python3
    print("{} and this is {}".format(key,val))

最后:预先警告python中的词典arbitrary order.如果您希望订购始终相同,则使用collections.OrderedDict会更安全。否则,您需要依赖于实施细节。想亲眼看看吗?制作ex_dict = {1:"how",3:"do you",7:"dotoday", 9:"hi"}

import collections
ex_dict= collections.OrderedDict([(1,"how"),(3,"do you"),(7,"dotoday")])
for key, val in ex_dict.iteritems(): #ex_dict.items() in python3
    print("{} and this is {}".format(key,val))

答案 2 :(得分:0)

替换

string= key," and this is ", ex_dict[key]

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

在python中,你用+而不是

连接字符串

,用于元组

答案 3 :(得分:0)

替换

string= key," and this is ", ex_dict[key]

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

答案 4 :(得分:0)

您可以使用-Des.node.client=truestr.join,它更易读,更不容易出现简单错误:

str.format

输出:

ex_dict = {1: "how",3: "do you",7: "dotoday"}
print("\n".join(["{} and this is {}".format(*tup) 
                for tup in ex_dict.items()]))

或者使用python3或使用1 and this is how 3 and this is do you 7 and this is dotoday 和python2,您可以解压缩并使用sep关键字:

from __future__ import print_function

输出:

ex_dict = {1: "how", 3: "do you", 7: "dotoday"}
print(*("{} and this is {}".format(*tup) 
        for tup in ex_dict.items()), sep="\n")