Coderr
Coderr

Reputation: 23

remove unnecessary comma from python dict

My dict is,

d= {'add1':'','add2':'address2','add3':'' }

I want to join all the values as a list of comma separated words.

if d is d= {'add1':'','add2':'address2','add3':'' }

then output would be address2

if d is d= {'add1':'address1','add2':'address2','add3':'' }

then output would be address1,address2

if d is d= {'add1':'address1','add2':'address2','add3':'address3' }

then output would be address1,address2,address3

if d is d= {'add1':'','add2':'','add3':'' }

then output would be '' (simply blank string)

What I have tried ?

",".join([d.get('add1',''), d.get('add2',''), d.get('add3','')])

but I am not getting output as I expected.

Upvotes: 2

Views: 974

Answers (5)

Christian Witts
Christian Witts

Reputation: 11585

If you don't need to worry about order

','.join(value for value in d.itervalues() if value)

If your keys are always add1 etc, they will be easily sortable to ensure order

','.join(d[key] for key in sorted(d.keys()) if d[key])

Upvotes: 4

Anand S Kumar
Anand S Kumar

Reputation: 90889

You can use list comprehension after getting d.values() and then str.join() -

','.join([v for v in d.values() if v])

Demo -

>>> d= {'add1':'','add2':'address2','add3':'' }
>>> ','.join([v for v in d.values() if v])
'address2'
>>> d= {'add1':'address1','add2':'address2','add3':'' }
>>> ','.join([v for v in d.values() if v])
'address1,address2'
>>> d= {'add1':'','add2':'','add3':'' }
>>> ','.join([v for v in d.values() if v])
''
>>> d= {'add1':'address1','add2':'address2','add3':'address2' }
>>> ','.join([v for v in d.values() if v])
'address1,address2,address2'

Upvotes: 1

Miketsukami
Miketsukami

Reputation: 524

Use dict.values() method and filter function:

','.join(filter(None, d.values()))

Upvotes: 0

luator
luator

Reputation: 5017

You have to filter out the empty stings first:

",".join([x for x in d.values() if x])

Upvotes: 1

Łukasz Rogalski
Łukasz Rogalski

Reputation: 23203

You may simply join non-empty values:

','.join(v for v in d.itervalues() if v)

Upvotes: 2

Related Questions