patternpythonMajor
Flattening a dictionary into a string
Viewed 0 times
dictionaryintostringflattening
Problem
Given:
I want to flatten into the string:
This is the ugly way that I'm achieving this right now:
I'm sure my developer colleagues are going to chastize me for this code. Surely there is a better way.
k = {'MASTER_HOST': '10.178.226.196', 'MASTER_PORT': 9999}I want to flatten into the string:
"MASTER_HOST='10.178.226.196', MASTER_PORT=9999"This is the ugly way that I'm achieving this right now:
result = []
for i,j in k.iteritems():
if isinstance(j, int):
result.append('%s=%d' % (i,j))
else:
result.append("%s='%s'" % (i,j))
', '.join(result)I'm sure my developer colleagues are going to chastize me for this code. Surely there is a better way.
Solution
For python 3.0+ (as @Serdalis suggested)
Older versions:
', '.join("{!s}={!r}".format(key,val) for (key,val) in k.items())Older versions:
', '.join("%s=%r" % (key,val) for (key,val) in k.iteritems())Code Snippets
', '.join("{!s}={!r}".format(key,val) for (key,val) in k.items())', '.join("%s=%r" % (key,val) for (key,val) in k.iteritems())Context
StackExchange Code Review Q#7953, answer score: 33
Revisions (0)
No revisions yet.