How can I convert a list of values to a dictionary in python? -
i have (unsorted) dictionary, keys start @ 0.0 , continue 0.1, 0.2, 0.3 , on. values numbers too. have sys.argv input, called 'a', float. need new dictionary, keys should be:
a a+0.1 a+0.2 a+0.3
... until values in original dict assigned key. values should remain same. final dictionary should be:
{a:first item of sorted dict, a+0.1:second item of sorted dict,...}
so basically, keys should added size of float 'a'.
i tried converting unsorted dictionary sorted list this:
list=[] in sorted(dict.keys()): list.append(dict[i])
now have sorted list of values of original dict need assign new keys.
use ordereddict maping of increment keys , values:
>>> collections import ordereddict >>> d = {0.1:1,0.2:2} >>> d {0.2: 2, 0.1: 1} >>> od = ordereddict(d) >>> od ordereddict([(0.2, 2), (0.1, 1)]) >>> newordereddict = ordereddict(map(lambda (x,y): (x+5, y), od.items())) >>> newordereddict ordereddict([(5.2, 2), (5.1, 1)])
mind ordereddict keeps inserting order not value order, if want value order sort mapped list before building new ordereddict
>>> newordereddict = ordereddict(sorted(map(lambda (x,y): (x+5, y), od.items()), key=lambda (x,y):x)) >>> newordereddict ordereddict([(5.1, 1), (5.2, 2)])
Comments
Post a Comment