我可以使用键列表访问嵌套的dict吗?

时间:2018-02-16 13:08:28

标签: python python-3.x dictionary

我想以编程方式访问字典。我知道如何使用递归函数执行此操作,但有更简单的方法吗?

example = {'a': {'b': 'c'},
           '1': {'2': {'3': {'4': '5'}}}}

keys = ('a', 'b')
example[keys] = 'new'
# Now it should be
#     example = {'a': {'b': 'new'},
#                '1': {'2': {'3': {'4': '5'}}}}


keys = ('1', '2', '3', '4')
example[keys] = 'foo'
# Now it should be
#     example = {'a': {'b': 'new'},
#                '1': {'2': {'3': {'4': 'foo'}}}}


keys = ('1', '2')
example[keys] = 'bar'
# Now it should be
#     example = {'a': {'b': 'new'},
#                '1': {'2': 'bar'}}

7 个答案:

答案 0 :(得分:4)

您似乎想要做的是定义您自己的支持这种索引的字典类。我们可以通过使用以下事实来获得相当简洁的语法:当您执行d[1, 2, 3]时,Python实际上将元组(1, 2, 3)传递给__getitem__

class NestedDict:
    def __init__(self, *args, **kwargs):
        self.dict = dict(*args, **kwargs)

    def __getitem__(self, keys):
        # Allows getting top-level branch when a single key was provided
        if not isinstance(keys, tuple):
            keys = (keys,)

        branch = self.dict
        for key in keys:
            branch = branch[key]

        # If we return a branch, and not a leaf value, we wrap it into a NestedDict
        return NestedDict(branch) if isinstance(branch, dict) else branch

    def __setitem__(self, keys, value):
        # Allows setting top-level item when a single key was provided
        if not isinstance(keys, tuple):
            keys = (keys,)

        branch = self.dict
        for key in keys[:-1]:
            if not key in branch:
                branch[key] = {}
            branch = branch[key]
        branch[keys[-1]] = value

以下是使用示例

# Getting an item
my_dict = NestedDict({'a': {'b': 1}})
my_dict['a', 'b'] # 1

# Setting an item
my_dict = NestedDict()
my_dict[1, 2, 3] = 4
my_dict.dict # {1: {2: {3: 4}}}

# You can even get a branch
my_dict[1] # NestedDict({2: {3: 4}})
my_dict[1][2, 3] # 4

然后,您还可以定义NestedDict__iter____len__,从而使__contains__实施更加丰富。

此外,这可以很容易地集成到您的代码中,因为任何预先存在的字典都可以通过NestedDict(your_dict)转换为嵌套字典。

答案 1 :(得分:1)

此解决方案创建另一个具有相同键的字典,然后更新现有字典:

cd code/clang-variables 
docker run -it -v $PWD:/home clang 
root@5196c095092d:/home# ./clang-variables test.cpp -- -std=c++14 

使用字符串,列表或元组来访问密钥

答案 2 :(得分:0)

在适应this answer(基本上是化妆品)后,我得到了:

from functools import reduce
import operator

def nested_get(dictionary, *keys):
    return reduce(operator.getitem, keys, dictionary)

def nested_set(dictionary, value, *keys):
    nested_get(dictionary, *keys[:-1])[keys[-1]] = value


example = {
    'a': {'b': 'c'},
    '1': {
        '2': {
            '3': {'4': '5'}
        }
    }
}

nested_set(example, "foo", "1", "2", "3")
print(example)

keys = ["1", "2"]
nested_set(example, "yay", *keys)
print(example)

输出:

{'a': {'b': 'c'}, '1': {'2': {'3': 'foo'}}}
{'a': {'b': 'c'}, '1': {'2': 'yay'}}

相同的想法(使用变量通过引用传递的事实),但这次调整one of my answers

def nested_set(element, value, *keys):
    if type(element) is not dict:
        raise AttributeError('nested_set() expects dict as first argument.')
    if len(keys) < 2:
        raise AttributeError('nested_set() expects at least three arguments, not enough given.')

    _keys = keys[:-1]
    _element = element
    for key in _keys:
        _element = _element[key]
    _element[keys[-1]] = value

example = {"foo": { "bar": { "baz": "ok" } } }
nested_set(example, "yay", "foo", "bar")
print(example)

输出

{'foo': {'bar': 'yay'}}

这个不需要任何花哨的进口,所以我倾向于更喜欢它.. 选择你的味道

答案 3 :(得分:0)

您可以使用较小的递归函数和字典理解:

import functools
def all_examples(f):
   def wrapper():
      def update_dict(d, path, target):
         return {a:target if path[-1] == a else update_dict(b, path, target) if isinstance(b, dict) else b for a, b in d.items()}
      current_d = {'a': {'b': 'c'},'1': {'2': {'3': {'4': '5'}}}}
      final_ds = []          
      for i in f():
         current_d = update_dict(current_d, *i)
         final_ds.append(current_d)
      return final_ds
   return wrapper

@all_examples
def input_data():
  return [[('a', 'b'), 'new'], [('1', '2', '3', '4'), 'foo'], [('1', '2'), 'bar']]

for i in input_data():
  print(i)

输出:

{'a': {'b': 'new'}, '1': {'2': {'3': {'4': '5'}}}}
{'a': {'b': 'new'}, '1': {'2': {'3': {'4': 'foo'}}}}
{'a': {'b': 'new'}, '1': {'2': 'bar'}}

答案 4 :(得分:0)

遍历您字典的方法。您可以通过继承dict

来轻松完成此操作

遍历算法是@MartijnPeters的礼貌(在那里)。

import operator

class ndict(dict):

    def get_traverse(self, mapList):
        return reduce(operator.getitem, mapList, self)

    def set_traverse(self, mapList, value):
        self.get_traverse(mapList[:-1])[mapList[-1]] = value

d = ndict({'a': {'b': 'c'}, '1': {'2': {'3': {'4': '5'}}}})

d.get_traverse(['a', 'b'])     # 'c'
d.set_traverse(['a', 'b'], 4)  # {'a': {'b': 4}, '1': {'2': {'3': {'4': '5'}}}}

答案 5 :(得分:0)

我想添加对dict-digger的引用,这是一个我有时想要使用的开源模块,它提供了开箱即用的功能。 (我与该项目无关)

答案 6 :(得分:0)

我结合了jpp和OlivierMelançon的答案来创建一个NestedDict类。我更喜欢像通常访问字典一样访问字典,然后使用列表作为参数

import operator
from functools import reduce

class NestedDict(dict):
    def __getitem__(self, item):
        if isinstance(item, list):
            return self.get_traverse(item)
        return super(NestedDict, self).__getitem__(item)

    def __setitem__(self, key, value):
        if isinstance(key, list):
            for _key in key[:-1]:
                if not _key in self:
                    self[_key] = {}
                self = self[_key]
            self[key[-1]] = value
            return self
        return super(NestedDict, self).__setitem__(key, value)

    def get_traverse(self, _list):
        return reduce(operator.getitem, _list, self)



nested_dict = NestedDict({'aggs': {'aggs': {'field_I_want': 'value_I_want'}, 'None': None}})
path = ['aggs', 'aggs', 'field_I_want']
nested_dict[path]  # 'value_I_want'

nested_dict[path] = 'changed'
nested_dict[path]  # 'changed'

编辑

对于任何有兴趣的人。我使用自动查找路径的功能增强了该类。 (在doctest中使用)

import operator
from functools import reduce
from copy import deepcopy

class NestedDict(dict):
    """
    Dictionary that can use a list to get a value

    :example:
    >>> nested_dict = NestedDict({'aggs': {'aggs': {'field_I_want': 'value_I_want'}, 'None': None}})
    >>> path = ['aggs', 'aggs', 'field_I_want']
    >>> nested_dict[path]
    'value_I_want'
    >>> nested_dict[path] = 'changed'
    >>> nested_dict[path]
    'changed'
    """
    def __getitem__(self, item):
        if isinstance(item, list):
            return self.get_traverse(item)
        return super(NestedDict, self).__getitem__(item)

    def __setitem__(self, key, value):
        if isinstance(key, list):
            for _key in key[:-1]:
                if _key not in self:
                    self[_key] = {}
                self = self[_key]
            self[key[-1]] = value
            return self
        return super(NestedDict, self).__setitem__(key, value)

    def get_traverse(self, _list):
        return reduce(operator.getitem, _list, self)

    _paths = []
    _path = []
    def find(self, key, _dict=None, _main_loop=True):
        """ Find a list of paths to a key

        :param key: str, the key you want to find
        :param _dict: used for recursive searching
        :return: list with paths
        :example:
        >>> nested_dict = NestedDict({'aggs': {'aggs': {'field_I_want': 'value_I_want'}, 'None': None}})
        >>> paths = nested_dict.find('field_I_want')
        >>> paths
        [['aggs', 'aggs', 'field_I_want']]
        >>> nested_dict[paths[0]] = 'changed'
        >>> nested_dict[paths[0]]
        'changed'
        """
        if _main_loop:
            self._path, self._paths = [], []
            _dict = self

        for _key in _dict.keys():        
            self._path.append(_key)

            if _key == key:
                self._paths.append(deepcopy(self._path)) 

            if isinstance(_dict[_key], dict):
                self.find(key, _dict[_key], _main_loop=False)

            self._path.pop()

        if _main_loop:
            return self._paths
相关问题