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

2024-10-02 18:26:38 发布

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

我有以下代码:

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

我似乎不知道如何去掉输出中的字典格式。你知道吗


Tags: andkey代码inyouforstringis
3条回答

你看的不是字典格式,而是tuples。你知道吗

In Python, multiple-element tuples look like:

1,2,3

The essential elements are the commas between each element of the tuple. Multiple-element tuples may be written with a trailing comma, e.g.

1,2,3,

but the trailing comma is completely optional. Just like all other expressions in Python, multiple-element tuples may be enclosed in parentheses, e.g.

(1,2,3)

or

(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))

替换

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

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

在python中,用+而不是

,用于元组

只需使用+组合字符串:

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

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

相关问题 更多 >