Reputation: 7633
For example:
d = {'a':'1', 'b':'2', 'c':'3'}
I want to get ds as a str:
ds = 'a:1, b:2, c:3'
My conversion function:
def convert_dict(my_dict):
converted = ''
for key, value in my_dict.items():
converted += key + ':' + value + ','
return converted[0:-1]
I suspect there should be a better and simpler way to do this.
Upvotes: 1
Views: 61
Reputation: 1331
str_d = ", ".join([":".join([str(k), str(v)]) for k, v in d.items()])
Upvotes: 0
Reputation: 9047
d.items()
gives (key, value) so first create key:value
using map(':'.join, d.items())
then finally join them using ', '.join
', '.join(map(':'.join, d.items()))
#'a:1, b:2, c:3'
NOTE: both key and value should be str
if not u can use
', '.join(map(lambda x: f'{x[0]}:{x[1]}', d.items()))
Upvotes: 2
Reputation: 70267
There's nothing wrong with your approach. We can do it with comprehensions to make it a bit shorter. But your code is perfectly understandable as-is and is nothing to be ashamed of.
def convert_dict(my_dict):
return ', '.join(f"{key}:{value}" for key, value in my_dict.items())
If you're using Python older than 3.5, you'll need to use .format
rather than the f""
string syntax I use in my example above.
Upvotes: 5