python - Breaking a list in to parts by subject -
i have list of dictionaries. each list can assumed have dictionaries of same format. let's call format:
dict_sample={'a':0,'b':1} let's a random integer, while b can 1 of few numbers (or strings, matter). i'm wanting sort of a values b. instance, if had list follows:
a b 54 1 25 0 53 1 532 2 132 0 list=[{'a':54,'b':1},{'a':25,'b':0},{'a':53,'b':1},{'a':532,'b':2},{'a':132,'b':0}] i break down in 3 lists. lists include (order not important)
0 list-> [25,132] 1 list-> [54,53] 2 list-> [532] i know can break a's list follows, can't quite figure out elegant solution sorting a's b's. suggestions? code far looks like:
[row['a'] row in list] what this:
index=0 #this looped through, or chosen 1 specific value [row['a'] if row['b']==index row in list]
if knew b values, trivial. want list each b value, each 1 has of a values in each dictionary b value. can translate directly english comprehension:
[[d['a'] d in lst if d['b']==b] b in bs] you don't have b values, can them doing pass:
bs = (d['b'] d in lst) except want unique values, , want iterate them in sorted order, so:
bs = sorted(set(d['b'] d in lst)) and that's there it. putting together:
>>> lst=[{'a':54,'b':1},{'a':25,'b':0},{'a':53,'b':1},{'a':532,'b':2},{'a':132,'b':0}] >>> bs = sorted(set(d['b'] d in lst)) >>> [[d['a'] d in lst if d['b']==b] b in bs] [[25, 132], [54, 53], [532]]
Comments
Post a Comment