List Access Dictionary

I have a data source that is best modeled with a dictionary (it is a set of key = value pairs ). For the specific purpose of visualization, I need to provide a list access interface (in addition to the regular dictionary interface), which means you have 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 the appropriate facade implementation - if I store the indexes as a dictionary key:

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

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

data["mykey"] = "myval"

I need to list all the keys and values ​​in a temporary list before I can return the items.

Please note that all of these implementations assume that I am using OrderedDict.

How would you provide both interfaces?

, PyQt QAbstractTableModel, - .

.

+5
4

, 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 ). , , self.byid[id][field] = newval. Python (), , self.byid, , self.data. .

+3

list(data.items())[12] (key, value) 13- - OrderedDict. list(data.keys())[12] 13- , list(data.values())[12] 13- .

, , dict s, - .

( , , OrderedDict __repr__: return '%s(%r)' % (self.__class__.__name__, list(self.items())))

+1

A 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')

EDIT:. , .

0

dict {} , , dict, / 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] .

0

All Articles