将字典键连接成字符串

3
我是一个有用的助手,可以将文本翻译成中文。
我有14本字典,它们都包含相同的信息键(例如时间、日期等),但值不同。我正在尝试构建一个函数,当字典作为参数列在函数中时,它将组合一句话。
如果我有一个字典:
dic1 = {'Name': 'John', 'Time': 'morning'}

我想将它们连接成一个字符串:

print 'Hello ' + dic1['Name']+', good ' + dic1['Time']+ '.'

我该怎么做呢?
注:抱歉,这会返回错误:
TypeError: can only concatenate list (not "str") to list

你想要连接键或值吗? - Rohit Jain
我想通过调用键来获取值。dic[]是一个错误,应该说dic1[]。 - B-mo
1
这段代码没有任何错误。 - alexvassel
3个回答

6
我认为你的意思是“插值”,而不是“连接”。
print "Hello %(Name)s, good %(Time)s" % dic1

2

使用新风格的字符串格式化(Python 2.6或更高版本):

print("Hello {Name}, good {Time}.".format(**dic1))

关于你的错误,我无法通过你提供的代码进行解释。如果你尝试将字符串__add__到列表中,你会得到这个错误:
>>> [45,3] + "foo"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list

但是将列表添加到字符串中(如果您的字典的值是一个列表,那么这就是您将使用示例代码执行的操作)会产生稍微不同的错误:

>>> "foo" + [45,3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'list' objects

-1
web_response = {2L: 67.0, 3L: 13.67, 4L: 10.25, 5L: 11.8, 6L: 11.83}

我有一个名为“web_response”的字典,为了将字典与字符串连接起来,我使用了逗号“,”。
print "web_response=", web_response

输出:

web_response= {2L: 67.0, 3L: 13.67, 4L: 10.25, 5L: 11.8, 6L: 11.83}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接