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.
source share