以列表形式访问字典

发布于 2024-11-16 21:40:37 字数 683 浏览 2 评论 0原文

我有一个最好用字典建模的数据源(它key=value对的集合)。为了特定的可视化目的,我需要提供一个类似列表的数据访问接口(除了常规字典接口之外),这意味着您应该能够执行以下操作:

data["mykey"] # returns the associated value
data[12][0] # returns the 13th key in the dictionary
data[12][1] # returns the 13th value in the dictionary

我找不到合适的外观实现 - 如果我存储索引作为字典键:

data[12] = ("mykey", "myval")

我可以轻松解决后两种情况,但我失去了执行第一种情况的能力。如果我像这样存储数据,

data["mykey"] = "myval"

则必须先枚举临时列表中的所有键和值,然后才能返回元素。

请注意,所有这些实现都假设我使用的是 OrderedDict

您将如何提供这两个接口?

如果您好奇,这是为了创建 PyQt QAbstractTableModel,其中底层数据容器是字典。

谢谢。

I have a data source which is best modeled with a dictionary (it is a collection of key=value pairs). For a specific visualization purpose, I need to provide a list-like data access interface (in addition to the regular dictionary interface), meaning that you should be able to do the following:

data["mykey"] # returns the associated value
data[12][0] # returns the 13th key in the dictionary
data[12][1] # returns the 13th value in the dictionary

I cannot find an appropriate facade implementation - if I store the indices as the dictionary key:

data[12] = ("mykey", "myval")

I can easily solve the last two cases, but I loose the ability to do the first. If I store data like

data["mykey"] = "myval"

I have to enumerate all keys and values in a temporary list before I can return elements.

Notice that all this implementations assume I am using an OrderedDict.

How would you provide both interfaces?

If you are curious, this is for creating a PyQt QAbstractTableModel where the underlying data container is a dictionary.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

蒗幽 2024-11-23 21:40:37

我必须做同样的事情来表示 ListCtrl 中的数据,这些数据有时需要通过键而不是索引来访问(这样,如果我获得任意值来定位,则不必搜索它)。如果您有一个字典列表,我发现最好的方法是创建另一个字典,其中引用相同的项目,但可以通过键访问。这成为我的数据加载方法:

  def SetData(self, cols, data):
    for idx, row in enumerate(data):
      item = dict((k, v.rstrip() if hasattr(v, 'rstrip') else v) for k, v in zip(cols, row))

      self.data[idx] = item

      self.byid[row[0]] = item

所以我有一个可以在 self.data 中访问的字典列表,然后是 self.byid 中的另一个字典,它保留相同的项目,但是通过 id 列(在本例中是我的行中的第 0 列) 。当我需要更新的时候,只要拿到一个ID,就可以调用self.byid[id][field] = newval。因为Python中的一切都是指针(引用),所以改变存储在self.byid中的字典的值会反映在存储在self.data中的字典列表中。就像魅力一样。

I have to do the same thing to represent data in a ListCtrl that needs to be accessible by a key rather than by index at times (so that it does not have to be searched if I get an arbitrary value to locate). If you have a list of dictionaries, the best I found was to create another dictionary with references to the same items, but accessible by key. This becomes my data load in method:

  def SetData(self, cols, data):
    for idx, row in enumerate(data):
      item = dict((k, v.rstrip() if hasattr(v, 'rstrip') else v) for k, v in zip(cols, row))

      self.data[idx] = item

      self.byid[row[0]] = item

So I have a list of dictionaries accessible in self.data, and then another dictionary in self.byid that keeps the same items, but by the id column (column 0 in my rows in this case). When I need to update, as long as I get an ID, I can call self.byid[id][field] = newval. Because everything in Python is a pointer (reference), changing the value of the dictionary stored in self.byid is reflected in the list of dictionaries stored in self.data. Works like a charm.

〗斷ホ乔殘χμё〖 2024-11-23 21:40:37

list(data.items())[12] 将返回 OrderedDict(key, value) 元组>。 list(data.keys())[12] 将单独返回第 13 个键,而 list(data.values())[12] 将返回第 13 个键价值。

不过,对于大型 dict 来说,这可能不是一个好主意,因为每次都会重新创建列表。

(但是,它与 OrderedDict 在其 __repr__ 方法中使用的方法完全相同:return '%s(%r)' % (self.__class__.__name__,列表(self.items())))

list(data.items())[12] will return a (key, value) tuple for the 13th key-value pair in your OrderedDict. list(data.keys())[12] will return the 13th key on its own, and list(data.values())[12] will return the 13th value.

This probably isn't a good idea for large dicts, though, due to the list being recreated each time.

(However, it's the very same method used by OrderedDict in its __repr__ method: return '%s(%r)' % (self.__class__.__name__, list(self.items())))

纸伞微斜 2024-11-23 21:40:37

获取您的 dict{} 并创建另一个字典,其中键是索引,值是原始字典的键,或者是原始字典的元组/列表。

d = {"key1":"value1","key2":"value2","key3":"value3"}
d2 = {1:"key1",2:"key2",3:"key3"}

然后:

d[d2[3]]

返回

'value3'

或者使用以下内容定义 d2:

d2 = {1:["key1","value1"],2:["key2","value2"],3:["key3","value3"]}

使用 d2[3][0] 和 d2[3][1] 作为密钥获取所需的访问权限,分别值。

Take your dict{} and create another one where the keys are indicies and the values are either the keys to the original dict, or a tuple/list from the original dict.

d = {"key1":"value1","key2":"value2","key3":"value3"}
d2 = {1:"key1",2:"key2",3:"key3"}

Then:

d[d2[3]]

returns

'value3'

Or defining d2 using the following:

d2 = {1:["key1","value1"],2:["key2","value2"],3:["key3","value3"]}

Gets you the access you wanted using d2[3][0] and d2[3][1] for the key and value respectively.

〆一缕阳光ご 2024-11-23 21:40:37

尝试基于索引的键访问但故障转移到默认键访问的 dict 子类可能会完成这项工作。类似以下内容:

from collections import OrderedDict

class IndexableDict(OrderedDict):
    def __getitem__(self, key):
        """Attempt to return based on index, else try key"""
        try:
            _key = self.keys()[key]
            return (_key, super(IndexableDict, self).__getitem__(_key))
        except (IndexError, TypeError):
            return super(IndexableDict, self).__getitem__(key)

d = IndexableDict(spam='eggs', messiah=False)
d['messiah'] ## False
d[1] ## ('messiah', False)
d[0] ## ('spam', 'eggs')

编辑:如果您使用整数作为键,这将会中断。

A dict subclass that attempts index-based access of keys but fails over to default key access might do the job. Something along the lines of:

from collections import OrderedDict

class IndexableDict(OrderedDict):
    def __getitem__(self, key):
        """Attempt to return based on index, else try key"""
        try:
            _key = self.keys()[key]
            return (_key, super(IndexableDict, self).__getitem__(_key))
        except (IndexError, TypeError):
            return super(IndexableDict, self).__getitem__(key)

d = IndexableDict(spam='eggs', messiah=False)
d['messiah'] ## False
d[1] ## ('messiah', False)
d[0] ## ('spam', 'eggs')

EDIT: This will break if you use integers as keys.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文