python - Spacing inbetween letters and numbers -
so basically, i'm trying write filter can separate numbers , letters dictionary , have space inbetween them. instance 12346 s
12346 q
.
def check_if_works(): dict_info = {} dict_info['1234'] = "test" dict_info['12456s'] = "test" dict_info['12456q'] = "test" dict_info['12456b'] = "test" dict_info['123456'] = "test" dict_info['asdftes'] = "test" dict_info['asdftess'] = "test" dict_info['asdftessd'] = "test" arr = [] key,value in dict_info.iteritems(): if key.isalpha() or key.isdigit(): pass #print key else: print key
no need list of dictionaries, want fill , dump new_dict directly.
also, there's no need try/except (which not work because str.isalpha()
never throw exceptions), should combine checks test contains letters or numbers (isalnum()
) , not contain either letters (isalpha()
) or numbers (isdigit()
).
then don't write file once per iteration step on original dictionary, once in end dump entire result dictionary.
new_dict = {} key,value in dict_info.iteritems(): check = key.isalnum() , not (key.isalpha() or key.isdigit()) new_dict[insert_spaces(key)] = value print (key, ":", value) open('output.json', 'wb') outfile: json.dump(new_dict, outfile, indent=4)
the function insert_spaces
need insert space between digit+letter or letter+digit looks this:
import re def insert_spaces(key): return re.sub(r'(\d)(\d)', r"\1 \2", re.sub(r'(\d)(\d)', r"\1 \2", key))
alternatively replace whole code dictionary comprehension (since python 2.7):
with open('output.json', 'wb') outfile: json.dump({ insert_spaces(key): dict_info[key] key in dict_info if key.isalnum() , not (key.isalpha() or key.isdigit()) }, outfile, indent=4)
or nicer formatted extracting check condition lambda function:
check_key = lambda key: key.isalnum() , not (key.isalpha() or key.isdigit()) open('output.json', 'wb') outfile: json.dump({ insert_spaces(k): dict_info[k] k in dict_info if check_key(k) }, outfile, indent=4)
Comments
Post a Comment