Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert empty dictionary to empty string

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

I need an empty string instead.

like image 591
mr_bulrathi Avatar asked Feb 14 '16 08:02

mr_bulrathi


People also ask

Can dict key empty string Python?

You can't use an empty string. The format strictly limits keys to valid Python identifiers, which means they have to have at least 1 letter or underscore at the start. So the field_name is either an integer or a valid Python identifier.

How do you make a dictionary empty?

To create an empty dictionary, first create a variable name which will be the name of the dictionary. Then, assign the variable to an empty set of curly braces, {} . Another way of creating an empty dictionary is to use the dict() function without passing any arguments.

How do you turn a dictionary into a Stric?

The ast. literal. eval() is an inbuilt python library function used to convert string to dictionary efficiently. For this approach, you have to import the ast package from the python library and then use it with the literal_eval() method.

Can dictionary values empty?

Python empty dictionary means that it does not contain any key-value pair elements. To create an empty dictionary in this example, we can use a dict(), which takes no arguments. If no arguments are provided, an empty dictionary is created.


2 Answers

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}"
like image 143
zangw Avatar answered Oct 16 '22 10:10

zangw


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.

like image 8
Remi Crystal Avatar answered Oct 16 '22 08:10

Remi Crystal