python 2.7 - How to sort defaultdict(list) such that all lists are sorted based on one key? -
to amazing programmers,
i know how can sort defaultdict(list) collection such sort order of 1 list (e.g. defaultdict(list)[list1]) applied remaining lists well. perhaps short description/example more useful. if there better way of doing ears.
example problem: had .csv file consisting of many columns (different data types) , headerline. using defaultdict(list) import .csv file using:
data = defaultdict(list) reader = csv.dictreader(open(filepath, 'r')) (k,v) in row.items(): data[k].append(v)
now left defaultdict(list) named 'data' of structure:
data = [('vara', <list of n time.struct_time items>), ('varb', <list of n other data type items>)', ('varc', <list of n other data type items>)']
each list (vara, varb, varc) has exact same number of items. assuming vara not ordered, how order data entries based on vara.
i know
sortorder = [i[0] in sorted(enumerate(data['vara']), key=lambda x:x[1])]
returns list correct order of indexes. there way apply order other lists.
note: read somewhere that
data[varb] = data[varb][sortorder] data[varc] = data[varc][sortorder]
would give me correct answer, given sortorder array (its not, above yields list). problem how can i, without using numpy, convert sortorder list array.
i think would:
- pair list vara numbers 1 n, so:
[ b, a, c ]
becomes[ (1,b), (2,a), (3,c) ]
- sort new list value, so:
[ (2,a), (1,b), (3,c) ]
- unpair them , way numbers end up, ordering other lists:
[2,1,3]
how make list order: take second item, first item, third item.
- for each row, take items in order new list
untested example code:
sort_holder = [(index, item) (index, item) in enumerate(data['vara'])] sort_holder = sorted(sort_holder, key = lambda pair: pair[1]) new_order = [pair[0] pair in sort_holder] var, row in data.items(): new_list = [] index in new_order: new_list.append(row[index]) data[var] = new_list
Comments
Post a Comment