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
I think you mean interpolate, not concatenate.
print "Hello %(Name)s, good %(Time)s" % dic1
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With