>>> d = {}
>>> s = str(d)
>>> print s
{}
I need an empty string instead.
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.
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.
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.
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.
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}"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With