我正在开发python实用程序。其中的一部分是生成一个文件索引。
在python中是否可以在不知道深度的情况下动态地访问多维字典。
如果我有示例数据:
example = {'main': {'2': {'2': '2-2', '1': '2-1'}, '1': {'2': '1-2', '1': '1-1'}}}
是否有一种方法可以使用类似于example["main","2","1"]的东西访问元素并返回2-1?我知道我可以写我自己的潜水算法,但我的经验表明,你不能写到这个值。
发布于 2016-11-21 20:17:02
如果您确实需要这样做,那么您将需要滚出自己的dict类。幸运的是,除了__getitem__之外,您可以从dict继承所有东西。
class MyDict(dict):
def __getitem__(self, keys):
if isinstance(keys, str):
# this special-case saves you if you try to do normal indexing
# on a string.
return super().__getitem__(keys)
cur = self
for key in keys:
cur = cur.get(key, {})
# the default option here returns an empty dict instead
# of raising a KeyError. That might not be what you want
return cur请注意,这将消除您通过元组进行密钥的能力,因此,除非对其进行了专门编码,否则将无法访问类似于{("some", "tuple", "values"): "any value"}的key/vals。可能看起来像..。
...
for i, key in enumerate(keys):
if keys[i:] in cur:
return cur[keys[i:]]
cur = cur.get(key, {})然后,您可以将您的映射转换到这个新的dict并以这种方式进行搜索。
example = {'main': {'2': {'2': '2-2', '1': '2-1'}, '1': {'2': '1-2', '1': '1-1'}}}
result = MyDict2(example)['2', '2', '1']您还提到了必须通过此设置值,在这种情况下也继承了__setitem__。
class MyDict(dict):
def __getitem__(self, keys):
# as above
def __setitem__(self, keys, value):
if isinstance(keys, str):
super().__setitem__(keys, value)
cur = self
for key in keys[:-1]:
cur = cur.setdefault(key, {})
cur[keys[-1]] = value发布于 2016-11-21 20:06:04
您可以这样做一个函数:
def get_item(d, keys):
current = d
for k in keys:
current = current[k] # You can add some error handling here
return current如果您想修改最后一个索引的值,您可以这样做。
def set_item(d, keys, new_value):
current = d
for k in keys[:-1]: # All the keys except the last one
current = current[k]
current[keys[-1]] = new_value发布于 2016-11-21 20:29:34
您还可以将@Arya提出的想法封装在派生的dict类中,例如:
class ListAccess(dict):
def __getitem__(self, item):
if type(item) in [tuple,list]:
item = list(item)
ret = self
while True:
try:
ret = ret[item.pop(0)]
except IndexError:
break
return ret
else:
return super(ListAccess, self).__getitem__(item)
store = ListAccess({'main': {'2': {'2': '2-2', '1': '2-1'}, '1': {'2': '1-2', '1': '1-1'}}})
print store['main','2','1']https://stackoverflow.com/questions/40728361
复制相似问题