python - Flatten dictionaries of list? -
using python 2.6.5, trying flatten lists attach each dictionary key , put them 1 list if possible 1 unique set. tried 2 different functions , not sure need do.
the problem i'm having it's not returning list of values list of keys.
for example:
dict = {'alpha': [[], ['dg1']], 'beta': [[], ['dg2'], ['dg3'], ['dg4'], ['dg1']], 'charlie': [[], ['dg1']], 'delta': [[], ['dg4']]} new_list = flatten(dict)
results in [alpha,beta,charile,delta]
, want [dg1,dg2,dg3,dg4]
.
what havve tried:
def flatten(a): b = [] c in a: if isinstance(c, list) , any(isinstance(i, list) in c): b.extend(flatten(c)) else: b.append(c) return b def flatten_list(lst): """ utility flatten list of list. if outer list not list or none, returns original object. return none none. """ if not isinstance(lst, list): return lst return sum(([x] if not isinstance(x, list) else flatten_list(x) x in lst), [])
think logic in part of code:
if isinstance(c, list) , any(isinstance(i, list) in c): b.extend(flatten(c)) else: b.append(c)
if c
list without lists inside, you're going append
onto b
, instead of extending
. so, if b = [0]
, c = [1, 2]
, you'll end b = [0, [1, 2]]
.
you need always extend if c
list. so, can this:
if isinstance(c, list): if any(isinstance(i, list) in c): b.extend(flatten(c)) else: b.extend(c) else: b.append(c)
this work. think happens if call flatten
on already-flat list, , should able simplify further.
meanwhile, if don't know how flatten each value in dict, can explicit loop:
d = {'alpha': [[], ['dg1']], 'beta': [[], ['dg2'], ['dg3'], ['dg4'], ['dg1']], 'charlie': [[], ['dg1']], 'delta': [[], ['dg4']]} new_d = {} k, v in d.items(): new_d[k] = flatten(v)
i've used d.items()
there. in python 2.x, gives new list, key-value pairs dictionary. if dictionary huge, making list loop on can wasteful, may want use d.iteritems()
instead, gives lazy iterator instead of list.
if know comprehensions are, should recognize pattern of "create empty collection, loop, add collection" paradigm case converting comprehension:
new_d = {k: flatten(v) k, v in d.items()}
unfortunately, dictionary comprehensions weren't added until 2.7. can same effect dict
function , generator expression:
new_d = dict((k, flatten(v)) k, v in d.items())
not quite readable, has same effect, , works 2.4.
Comments
Post a Comment