usingAppend = []; usingExtend = []; usingLC = []
d = {'pKey_b': 'vb1', 'pKey_e': 've1', 'pKey_c': 'vc1', 'pKey_a': 'va1', 'pKey_d': 'vd1'}
Using append
in the for-loop
gives a list
with sublists
for k, v in sorted(d.iteritems()):
usingAppend.append([k, v])
print '\n', usingAppend
'''
[
['pKey_a', 'va1'],
['pKey_b', 'vb1'],
['pKey_c', 'vc1'],
['pKey_d', 'vd1'],
['pKey_e', 've1']
]
'''
Using extend
in the for-loop
gives a single list
for k, v in sorted(d.iteritems()):
usingExtend.extend((k, v))
print '\n', usingExtend
'''
['pKey_a', 'va1', 'pKey_b', 'vb1', 'pKey_c', 'vc1', 'pKey_d', 'vd1', 'pKey_e', 've1']
'''
Using this generator expression gives the same results as using append
in a for loop
, a list
with sublists
usingLC = sorted([k, v] for k, v in d.iteritems())
print '\n', usingLC
'''
[
['pKey_a', 'va1'],
['pKey_b', 'vb1'],
['pKey_c', 'vc1'],
['pKey_d', 'vd1'],
['pKey_e', 've1']
]
'''
My question is, is there a way to set up the generator expression to give the same results as using extend
in a for-loop
You use double looping:
[i for k, v in sorted(d.iteritems()) for i in (k, v)]
or
[i for item in sorted(d.iteritems()) for i in item]
or itertools.chain.from_iterable()
:
from itertools import chain
list(chain.from_iterable(item for item in sorted(d.iteritems())))
although you could just use:
list(chain.from_iterable(sorted(d.iteritems())))
in these cases.
Demo:
>>> d = {'pKey_b': 'vb1', 'pKey_e': 've1', 'pKey_c': 'vc1', 'pKey_a': 'va1', 'pKey_d': 'vd1'}
>>> [i for k, v in sorted(d.iteritems()) for i in (k, v)]
['pKey_a', 'va1', 'pKey_b', 'vb1', 'pKey_c', 'vc1', 'pKey_d', 'vd1', 'pKey_e', 've1']
>>> from itertools import chain
>>> list(chain.from_iterable(item for item in sorted(d.iteritems())))
['pKey_a', 'va1', 'pKey_b', 'vb1', 'pKey_c', 'vc1', 'pKey_d', 'vd1', 'pKey_e', 've1']
>>> list(chain.from_iterable(sorted(d.iteritems())))
['pKey_a', 'va1', 'pKey_b', 'vb1', 'pKey_c', 'vc1', 'pKey_d', 'vd1', 'pKey_e', 've1']