Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python join equivalent

Tags:

python

join

I have a dictionary say..

dict = {
    'a' : 'b',
    'c' : 'd'
}

In php I would to something like implode ( ',', $dict ) and get the output 'a,b,c,d' How do I do that in python?

like image 330
Rob P. Avatar asked Apr 29 '11 04:04

Rob P.


2 Answers

This seems to be easiest way:

>>> from itertools import chain
>>> a = dict(a='b', c='d')
>>> ','.join(chain(*a.items()))
'a,b,c,d'
like image 112
Daniel Kluev Avatar answered Oct 18 '22 05:10

Daniel Kluev


First, the wrong answer:

','.join('%s,%s' % i for i in D.iteritems())

This answer is wrong because, while associative arrays in PHP do have a given order, dictionaries in Python don't. The way to compensate for that is to either use an ordered mapping type (such as OrderedDict), or to force an explicit order:

','.join('%s,%s' % (k, D[k]) for k in ('a', 'c'))
like image 25
Ignacio Vazquez-Abrams Avatar answered Oct 18 '22 03:10

Ignacio Vazquez-Abrams