Add strings with spaces to value of dictionary Python(2.7) + sort -
i reading input file called "id2" setup in format
9 6 15 42 word
i'm trying write script adds each line own dictionary (the number key , words follow value). currently, code works strings contain no whitespace (i.e. work first line " 9 " ). error receive 'valueerror: many values unpack'.
i need script print ' key : value ' result (not dictionary itself) , have sorted numerically. i'm pretty sure need dict.keys , list.sort i'm unsure how implement. following code far:
d = {} open("id2") f: line in f: (key, val) = line.split() d[int(key)] = val print d
this implementation addresses issues. adding maxsplits argument line.split()
break string in 1 place. argument none cause continuous whitespace removed between number , string. added val.rstrip()
remove newline present @ end of line. sorted key , printed each item out.
d = {} open("id2") f: line in f: (key, val) = line.split(none, 1) d[int(key)] = val.rstrip() key in sorted(d): print key, ':', d[key]
Comments
Post a Comment