Convert empty dictionary to empty string

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

I need an empty string.

+5
source share
5 answers

You can do this using the shortest path as shown below, since the dictionary is False and execute it using logical operators .

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

Or without str

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

If d not an empty dictionary, convert it to a string using str()

 >>> d['f'] = 12 >>> str(d or '') "{'f': 12}" 
+15
source

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

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

So 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 a dict string when something is in the dict.

+8
source

Take a look at the docs :

Verification of the value of truth

Any object can be checked for true, for use in an if or while condition or as an operand of boolean operations below. The following values ​​are considered false:

  • None
  • False
  • zero of any number type, for example 0 , 0.0 , 0j .
  • any empty sequence, for example '' , () , [] .
  • any empty mapping, for example {} .
  • instances of custom classes if the class defines a __bool__() or __len__() when this method returns the integer 0 or bool is False .

Thus, your empty dictionary will turn out to be False according to this bold rule. So you can use:

 d = {} if not d: s = '' else: s = str(d) 
+2
source

Convert each item in the dictionary to a string, then append them to an empty string,

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

I would suggest a sub classing dict and override 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'}" 
0
source

Source: https://habr.com/ru/post/1242975/


All Articles