python - 设置一个字典中包含另一字典路径的值

标签 python python-3.x

我有一个外部主字典,我在其中存储一些值,还有一个辅助字典,我用它来迭代仅一些名称和我定义的第一个字典的值,看起来像这样:

main_dict = {
    'colors': {
        'foo': 'orange',
        'bar': 'blue',
    },
    'fruits': {
        'xyz': 'apple',
        'abc': 'orange',
        'qwe': 'strawberry'

    }
}

secondary_dict = {
    'word1': main_dict['colors']['bar'],
    'word2': main_dict['fruits']['abc'],
    'word3': main_dict['colors']['foo']

}

#A function that iterates the keys from secondary_dict, does something, and outputs a new dictionary:
new_dict = my_function(secondary_dict)

当我创建完新字典后,我想将 BACK 写入用作辅助字典中的值的原始字典的路径,但我不知道该怎么做,所以从某种意义上说,它有点就像这样做:

secondary_dict = {
    'word1': main_dict['colors']['bar'],
    'word2': main_dict['fruits']['abc'],
    'word3': main_dict['colors']['foo']

}

对此:

main_dict['colors']['bar'] = new_dict['word1'],
main_dict['fruits']['abc'] = new_dict['word2'],
main_dict['colors']['foo'] = new_dict['word3']

或者在(不正确的)伪代码中:

for key, path in secondary_dict.items():
  path = new_dict[key]

我的第一个想法是不直接将路径存储在 secondary_dict 中,将它们作为字符串存储,而是翻转字典并使用 eval() 进行迭代。但据我所知,强烈建议不要使用 eval() ,因为总有“更好的方法”...

那么,有没有办法在不使用 eval() 的情况下完成我想做的事情?

(如果很难理解我想说的话,我深表歉意,我意识到这是一个相当具体的问题)

最佳答案

这是使用collections模块的方法。

它有两个部分:一个 Dict_Tree 类,它“扁平化”对嵌套字典的访问。 (似乎与 @Eugene K 的提议非常相似。)

还有一个 Proxy_Dict 类。这存储从简单键(如“word1”)到完整键(如(“colors”,“bar”))的映射,记录您分配给简单键的内容并将其即时写回主字典或仅根据要求。

import collections

class Dict_Tree(collections.UserDict):
    def __init__(self, data=None):
        super().__init__()
        if not data is None:
            self.data = data
    def __getitem__(self, key):
        node = self.data
        for k in key:
            node = node[k]
        return node
    def __setitem__(self, key, value):
        node = self.data
        for k in key[:-1]:
            node = node.setdefault(k, {})
        node[key[-1]] = value

class Proxy_Dict:
    def __init__(self, master, delayed_writeback=True, **map):
        self.delayed_writeback = delayed_writeback
        self.master = master
        if delayed_writeback:
            self.front = collections.ChainMap({}, master)
        else:
            self.front = master
        self.map = map
    def __getitem__(self, key):
        return self.front[self.map[key]]
    def __setitem__(self, key, value):
        self.front[self.map[key]] = value
    def keys(self):
        return self.map.keys()
    def values(self):
        return (self[k] for k in self.keys())
    def items(self):
        return ((k, self[k]) for k in self.keys())
    def __iter__(self):
        return iter(self.keys())
    def writeback(self):
        if self.delayed_writeback:
            self.master.update(self.front.maps[0])

in_dict = {
    'colors': {
        'foo': 'orange',
        'bar': 'blue',
    },
    'fruits': {
        'xyz': 'apple',
        'abc': 'orange',
        'qwe': 'strawberry'

    }
}

master = Dict_Tree(in_dict)
secondary = Proxy_Dict(master,
                       word1=('colors', 'bar'),
                       word2=('fruits', 'abc'),
                       word3=('colors', 'foo'))

secondary['word1'] = 'hello'
secondary['word2'] = 'world'
secondary['word3'] = '!'

secondary.writeback()

关于python - 设置一个字典中包含另一字典路径的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49090099/

相关文章:

python - 使用 python 根据不同文件中的键列进行映射

Python 文档字符串意外地没有

Python从命名管道获取数据

python - 如何从 csv 文件的两个特定列创建元组列表?

Python:两个函数之间的重叠(kde 和正常的 PDF)

python / Pandas : How to Match List of Strings with a DataFrame column

python - 如何在 Pandas DataFrame 中为我的预测结果添加一列,然后另存为 CSV?

python-3.x - 使用 Python3 ncclient/paramiko 时出错?

Python 要求用户输入而不换行?

python - 通过线程并行化缓慢的 api 调用