mr_bulrathi
mr_bulrathi

Reputation: 554

Convert empty dictionary to empty string

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

I need an empty string instead.

Upvotes: 5

Views: 2560

Answers (5)

BrockLee
BrockLee

Reputation: 981

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'}"

Upvotes: 0

elm
elm

Reputation: 20435

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

>>> ''.join(map(str,d))

Upvotes: 0

Sнаđошƒаӽ
Sнаđошƒаӽ

Reputation: 17612

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)

Upvotes: 2

zangw
zangw

Reputation: 48536

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}"

Upvotes: 16

Remi Guan
Remi Guan

Reputation: 22312

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.

Upvotes: 8

Related Questions