python join equivalent
I have a dictionary say..
dict = {
'a' : 'b',
'c' : 'd'
}
In php I would to something like implode ( ',', $开发者_Go百科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'))
Use string join on a flattened list of dictionary items like this:
",".join(i for p in dict.items() for i in p)
Also, you probably want to use OrderedDict.
This has quadratic performance, but if the dictionary is always small, that may not matter to you
>>> sum({'a':'b','c':'d'}.items(), ())
('a', 'b', 'c', 'd')
note that the dict.items() does not preserve the order, so ('c', 'd', 'a', 'b') would also be a possible output
a=[]
[ a.extend([i,j]) for i,j in dict.items() ]
Either
[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 is return each value from each pair in the mydict
Edit: Also put a ",".join() around these. I didn't read your question properly
I know this is an old question but it is also good to note.
The original question is misleading. implode() does not flatten an associative array in PHP, it joins the values
echo implode(",", array("a" => "b", "c" => "d"))
// outputs b,d
implode() would be the same as
",".join(dict.values())
# outputs b,d
This is not very elegant, but works:
result=list()
for ind in g:
result.append(ind)
for cval in g[ind]:
result.append(cval)
dictList = dict.items()
This will return a list of all the items.
精彩评论