Skip to content

Instantly share code, notes, and snippets.

@mensly
Last active December 21, 2015 10:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mensly/6291843 to your computer and use it in GitHub Desktop.
Save mensly/6291843 to your computer and use it in GitHub Desktop.
php-style argument parse thing
import re
def phpdict(src):
myDict = {}
for k, v in src.items():
pattern = re.search('([^[]+)((?:\[[^\]]*\])+)', k)
if pattern:
path = [(int(p) if p.isdigit() else p) for p in re.findall('\[([^\]]+)\]', k)]
new_key = pattern.group(1)
if new_key not in myDict:
myDict[new_key] = {}
store = myDict[new_key]
for element in path[:-1]:
if element not in store:
store[element] = {}
store = store[element]
store[path[-1]] = v
else:
myDict[k] = v
return myDict
if __name__ == '__main__':
blah = phpdict({'scales[1][width]': '544', 'scales[0][width]': '300',
'scales[1][name]': 'large', 'scales[0][name]': 'thumb',
'scales[0][height]': '300', 'scales[1][height]': '544',
'blah': 'something_else'})
print blah
print blah['scales'][0]
print blah['scales'][1]['height']
print blah['blah']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment