列表链接到字典值

时间:2017-05-28 11:35:16

标签: python list dictionary

我正在使用嵌套字典的复杂结构,我想使用一些以列表作为参数的函数。

有没有办法从字典中获取值列表,但保持两者的链接方式如果我修改另一个也会被修改?

让我举一个例子说明:

# I have this dictionary
d = {'first': 1, 'second': 2}

# I want to get a list like this
print(l) # shows [1, 2]

# I want to modify the list and see the changes reflected in d
l[0] = 23
print(l) # shows [23, 2]
print(d) # shows {'fist': 23, 'second': 2}

有没有办法实现类似的东西?

1 个答案:

答案 0 :(得分:2)

您必须创建一个包装字典的自定义sequence object,将索引映射回键以访问get或set值:

from collections.abc import Sequence

class ValueSequence(Sequence):
    def __init__(self, d):
        self._d = d
    def __len__(self):
        return len(self._d)
    def _key_for_index(self, index):
        # try to avoid iteration over the whole dictionary
        if index >= len(self):
            raise IndexError(index)
        return next(v for i, v in enumerate(self._d) if i == index)
    def __getitem__(self, index):
        key = self._key_for_index(index)
        return self._d[key]
    def __setitem__(self, index, value):
        key = self._key_for_index(index)
        self._d[key] = value
    def __repr__(self):
        return repr(list(self._d.values()))

该对象不支持删除,插入,追加或扩展。仅支持对现有字典值的操作。该对象也是 live ;如果您更改字典,该对象将直接反映这些更改。

演示:

>>> d = {'first': 1, 'second': 2}
>>> l = ValueSequence(d)
>>> print(l)
[1, 2]
>>> l[0] = 23
>>> print(l)
[23, 2]
>>> print(d)
{'first': 23, 'second': 2}
>>> d['second'] = 42
>>> l
[23, 42]

然而,这些并不一定有效。

继承Sequence ABC会给你一些奖励方法:

>>> l.index(42)
1
>>> l.count(42)
1
>>> 23 in l
True
>>> list(reversed(l))
[42, 23]

考虑到词典无序;上述对象将直接反映对字典的更改,如果此类更改导致不同的排序,那么这将导致值的不同顺序。但是,如果您不添加或删除密钥,字典的顺序将保持稳定。

相关问题