Skip to content

Instantly share code, notes, and snippets.

@BBischof
Created August 29, 2016 02:27
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 BBischof/290aabe58b1ea8cf175c4c9f38c5653d to your computer and use it in GitHub Desktop.
Save BBischof/290aabe58b1ea8cf175c4c9f38c5653d to your computer and use it in GitHub Desktop.
another iteration on the path-like dictionary access. This makes it into a class and uses getters and setters, a much more elegant solution
import sys, json
#inspired by http://stackoverflow.com/questions/14692690/access-python-nested-dictionary-items-via-a-list-of-keys
# Testing dictionary
D = {
"a": {
"aa": {
"aaa": 1,
"aab": 2
},
"ab": {
"aba": 3,
"abb": 4
}
},
"b": {
"ba": 5,
"bb": 6
},
"c": 7
}
# Some example paths
P1 = "a:aa:aaa" # 1
P2 = "a:aa:aab" # 2
P3 = "a:ab:aba" # 3
P4 = "a:ab" # {"aba": 3, "abb": 4}
P5 = "b:ba" # 5
P6 = "c" # 7
P7 = "a:ba:aba" # err
##Hardcoded delimiter##
# class path_lookup(object):
# def __init__(self, data):
# self.data = data
# def __getitem__(self, path):
# if path == "":
# return self.data
# else:
# path_list = path.split(":")
# try:
# return reduce(lambda d, k: d[k], path_list, self.data)
# except KeyError:
# print("[path_lookup] Innapropriate path: " + path)
# def __setitem__(self, path, value):
# if ":" not in path:
# self.data[path] = value
# else:
# path_list = path.rsplit(":",1)
# try:
# self.data[path_list[0]][path_list[1]] = value
# except KeyError:
# print "[path_set] Innapropriate destination path: " + path_list[0]
##this version takes lists!##
class path_lookup(object):
def __init__(self, data):
self.data = data
def __getitem__(self, path):
if path == []:
return self.data
else:
try:
return reduce(lambda d, k: d[k], path, self.data)
except KeyError:
print("[path_get] Innapropriate path: " + str(path))
def __setitem__(self, path, value):
print path
if len(path) == 1:
self.data[path] = value
else:
try:
reduce(lambda d, k: d[k], path[:-1], self.data)[path[-1]] = value
except KeyError:
print "[path_set] Innapropriate destination path: " + path
def main():
d = path_lookup(D)
print d[P1.split(":")]
print d[P2.split(":")]
print d[P3.split(":")]
print d[P4.split(":")]
print d[P5.split(":")]
print d[P6.split(":")]
print d[P7.split(":")]
d["a:here".split(":")] = 11
print d["a:here".split(":")]
if __name__=="__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment