Reputation: 49
I have 14 dictionaries all containing the same keys of information (i.e. time, date etc.) , but varying values. I'm trying to build a function that will put together a sentence when the dictionary is listed as the argument in the function.
If I have a dictionary:
dic1 = {'Name': 'John', 'Time': 'morning'}
And I want to concatenate them to a string:
print 'Hello ' + dic1['Name']+', good ' + dic1['Time']+ '.'
How would I go about this?
*Note, sorry, this returns the error:
TypeError: can only concatenate list (not "str") to list
Upvotes: 3
Views: 8662
Reputation: 10684
web_response = {2L: 67.0, 3L: 13.67, 4L: 10.25, 5L: 11.8, 6L: 11.83}
I've a dictionary named "web_response",For concatenation of dictionary with string I used comma ","
print "web_response=", web_response
Output:
web_response= {2L: 67.0, 3L: 13.67, 4L: 10.25, 5L: 11.8, 6L: 11.83}
Upvotes: -1
Reputation: 309831
Using new style string formatting (python2.6 or newer):
print("Hello {Name}, good {Time}.".format(**dic1))
As for your error, I can't explain it with the code you've provided above. If you try to __add__
a string to a list, you'll get that error:
>>> [45,3] + "foo"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list
But adding a list to a string (which is what you would be doing with the example code if your dictionary had a list as a value) gives a slightly different error:
>>> "foo" + [45,3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'list' objects
Upvotes: 2
Reputation: 77059
I think you mean interpolate, not concatenate.
print "Hello %(Name)s, good %(Time)s" % dic1
Upvotes: 6