Python equivalent equivalent

I have a dictionary.

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

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

+8
python join
source share
9 answers

This seems the easiest way:

 >>> from itertools import chain >>> a = dict(a='b', c='d') >>> ','.join(chain(*a.items())) 'a,b,c,d' 
+6
source share

Firstly, the answer is incorrect :

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

This answer is incorrect because, although associative arrays in PHP have this order, dictionaries in Python do not. The way to compensate for this is to either use an ordered display type (e.g. OrderedDict ), or force an explicit order to be set:

 ','.join('%s,%s' % (k, D[k]) for k in ('a', 'c')) 
+5
source share

Use the join string in a flattened list of dictionary items, for example:

 ",".join(i for p in dict.items() for i in p) 

Also, you probably want to use OrderedDict .

+4
source share

This has quadratic performance, but if the dictionary is always small, it may not matter to you.

 >>> sum({'a':'b','c':'d'}.items(), ()) ('a', 'b', 'c', 'd') 

note that dict.items () does not preserve order, so ('c', 'd', 'a', 'b') will also be a possible output

+2
source share
 a=[] [ a.extend([i,j]) for i,j in dict.items() ] 
+1
source share

Or

 [value for pair in {"a": "b", "c" : "d"}.iteritems() for value in pair] 

or

 (lambda mydict: [value for pair in mydict.iteritems() for value in pair])({"a": "b", "c" : "d"}) 

Explanation:

Simplified this example returns each value from each pair in mydict

Edit: also add β€œ,” around them. join (). I did not read your question correctly.

+1
source share

I know this is an old question, but it should also be noted.

The original question is misleading. implode () does not smooth an associative array in PHP, it combines values

 echo implode(",", array("a" => "b", "c" => "d")) // outputs b,d 

implode () will be the same as

 ",".join(dict.values()) # outputs b,d 
+1
source share

This is not very elegant, but it works:

 result=list() for ind in g: result.append(ind) for cval in g[ind]: result.append(cval) 
0
source share

dictList = dict.items ()

This will return a list of all items.

-one
source share

All Articles