Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate dictionary keys to a string

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
like image 302
B-mo Avatar asked Nov 30 '25 20:11

B-mo


2 Answers

I think you mean interpolate, not concatenate.

print "Hello %(Name)s, good %(Time)s" % dic1
like image 71
kojiro Avatar answered Dec 02 '25 10:12

kojiro


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
like image 26
mgilson Avatar answered Dec 02 '25 09:12

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!