marlon
marlon

Reputation: 7633

Is there a better way to convert a dict to string delimited by comma?

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

Answers (3)

Max Shouman
Max Shouman

Reputation: 1331

str_d = ", ".join([":".join([str(k), str(v)]) for k, v in d.items()])

Upvotes: 0

Epsi95
Epsi95

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

Silvio Mayolo
Silvio Mayolo

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

Related Questions