Skip to content

Instantly share code, notes, and snippets.

@lqez
Last active December 13, 2015 17:58
Show Gist options
  • Save lqez/4951310 to your computer and use it in GitHub Desktop.
Save lqez/4951310 to your computer and use it in GitHub Desktop.
Dict <-> String parser for NICE - KOREA INFORMATION SERVICE
#
# Dict <-> String parser for NICE - KOREA INFORMATION SERVICE (sigh)
#
# [email protected]
#
from itertools import izip
def encode(d):
res = []
for key in d.keys():
res.append('%d:%s%d:%s' % (len(key), key, len(str(d[key])), str(d[key])))
return ''.join(res)
def decode(s):
tokens = []
try:
while s is not '':
t = s.split(':', 1)
s = s[len(t[0])+1:]
tokens.append(s[:int(t[0])])
s = s[int(t[0]):]
except:
return None
i = iter(tokens)
return dict(izip(i, i))
def test():
s = '3:foo3:bar'
d = {'foo':'bar'}
assert(s == encode(d))
assert(d == decode(s))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment