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?
This seems to be easiest way:
>>> from itertools import chain
>>> a = dict(a='b', c='d')
>>> ','.join(chain(*a.items()))
'a,b,c,d'
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With