When the comprehension of the list becomes
- long
- incomprehensible / hard to read
- and most importantly don't work
pull them out and use the guide for cycle (s) each time:
Python 2.x
def unpack(d): for k, v in d.iteritems(): tmp = [] for subdict in v: for _, val in subdict.iteritems(): tmp.append(val) yield (k, tmp[0], tmp[1]) print list(unpack({'A':[{'x':1},{'x':2}], 'B':[{'x':3},{'x':4}] }))
Python 3.x
def unpack(d): for k, v in d.items(): tmp = [] for subdict in v: for _, val in subdict.items(): tmp.append(val) yield (k, *tmp)
Output:
[('A', 1, 2), ('B', 3, 4)]
source share