5
>>> d = {}
>>> s = str(d)
>>> print s
{}

I need an empty string instead.

gunr2171
  • 16,104
  • 25
  • 61
  • 88
mr_bulrathi
  • 514
  • 7
  • 23
  • 12
    I am very curious as to why there is a 500 rep bounty on this question. – BrockLee Feb 17 '16 at 19:40
  • @LeoCHan: ​​​​​​​​​​​​​​​I am very curious as to why your comment got 9 upvotes (now) also :P. Anyway, [the answer is that I want to be a 10ker](http://chat.stackoverflow.com/transcript/message/28795645#28795645). – Remi Guan Feb 24 '16 at 05:00

5 Answers5

16

You can do it with the shortest way as below, since the empty dictionary is False, and do it through Boolean Operators.

>>> d = {}
>>> str(d or '')
''

Or without str

>>> d = {}
>>> d or ''
''

If d is not an empty dictionary, convert it to string with str()

>>> d['f'] = 12
>>> str(d or '')
"{'f': 12}"
zangw
  • 43,869
  • 19
  • 177
  • 214
8

An empty dict object is False when you try to convert it to a bool object. But if there's something in it, it would be True. Like empty list, empty string, empty set, and other objects:

>>> d = {}
>>> d
{}
>>> bool(d)
False
>>> d['foo'] = 'bar' 
>>> bool(d)
True

So it's simple:

>>> s = str(d) if d else ''
>>> s
"{'foo': 'bar'}"
>>> d = {}
>>> s = str(d) if d else ''
>>> s
''

Or just if not d: s = '' if you don't need s be string of the dict when there's something in the dict.

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
  • @mr_bulrathi You can click the check sign to accept this as an answer to close the question. – Selcuk Feb 14 '16 at 08:36
  • @Selcuk: Ah, yes and no. *accepting* not *closing* ;) – Remi Guan Feb 14 '16 at 10:15
  • @KevinGuan "Closing" as in "not listed as unanswered anymore" :) – Selcuk Feb 14 '16 at 10:33
  • @Selcuk: Hey, it's not bad to answering a question which already has an accepted answer. Also we can change the accepted answer if it's better than the already accepted one. So I think, the "not listed as unanswered anymore" is incorrect in this case :P – Remi Guan Feb 14 '16 at 11:19
  • 1
    @KevinGuan You are right, but I am simply talking about this: http://stackoverflow.com/unanswered/tagged/python – Selcuk Feb 14 '16 at 11:37
  • @Selcuk: Ah, that one. Yeah you're correct. "Remove this question from that page". – Remi Guan Feb 14 '16 at 11:41
  • @KevinGuan here the **singe quote('')** wont work `s = str(d) if d else ''` but when i print it is showing null space but when i tried this with `s=str(d) if d else ""` it works we have to use **double quote ""** – Ankanna Feb 14 '16 at 17:48
  • @JohnAnkanna: Err...`''` is *nothing*, *not a space*. And `"" == ''`. They're the same thing. However, `'' != ' '`. – Remi Guan Feb 15 '16 at 01:10
2

Take a look at the docs:

Truth Value Testing

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

  • None
  • False
  • zero of any numeric type, for example, 0, 0.0, 0j.
  • any empty sequence, for example, '', (), [].
  • any empty mapping, for example, {}.
  • instances of user-defined classes, if the class defines a __bool__() or __len__() method, when that method returns the integer zero or bool value False.

So your empty dictionary turns out to be False according to that bolded rule. So you can use:

d = {}
if not d:
   s = ''
else:
   s = str(d)
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
0

Convert each item in the dictionary to a string, then join them with the empty string,

>>> ''.join(map(str,d))
elm
  • 20,117
  • 14
  • 67
  • 113
0

I would like to propose sub classing dict and overriding the __str__ method:

class DontForgetToDoYourTaxes(dict):
    def __str__(self):
        return self or ""

Then to use:

d = DontForgetToDoYourTaxes()
print d  # ""
d["ayy"] = "lmao"
print d  # "{'ayy': 'lmao'}"
BrockLee
  • 931
  • 2
  • 9
  • 24