10

Hi I am new to Python and I am struggling regarding how to print dictionary.

I have a dictionary as shown below.

dictionary = {a:1,b:1,c:2}

How can I print dictionary in one line as shown below?

a1b1c2

I want to print keys and values in one line but could not figure out by myself.

I would appreciate your advice!

yusuke0426
  • 273
  • 2
  • 4
  • 15

2 Answers2

16

With a dictionary, e.g.

dictionary = {'a':1,'b':1,'c':2}

You could try:

print ''.join(['{0}{1}'.format(k, v) for k,v in dictionary.iteritems()])

Resulting in

a1c2b1

If order matters, try using an OrderedDict, as described by this post.

Community
  • 1
  • 1
Stephen B
  • 1,246
  • 1
  • 10
  • 23
  • ```def format_dict(dictionary): return ' '.join(['{0}={1}'.format(k, v) for k,v in dictionary.iteritems()])``` – Alon Burg Mar 26 '19 at 11:01
6

If you want a string to contain the answer, you could do this:

>>> dictionary = {'a':1,'b':1,'c':2}
>>> result = "".join(str(key) + str(value) for key, value in dictionary.items())
>>> print(result)
c2b1a1

This uses the join method on an empty string. Dict's are not ordered, so the order of the output may vary.

Update - Using f-strings you could do this too:

>>> result = "".join(f"{key}{value}" for key, value in dictionary.items())
Brad Campbell
  • 2,969
  • 2
  • 23
  • 21
  • 1
    Note that in Python 3.6 dicts are now ordered (unless you mess with them a lot), so the order of the output in 3.6+ will be deterministic. – Brad Campbell Apr 03 '17 at 20:26