[英]Python: subclass or metaclass for an ordered collection of dictionaries
我是python的新手。 我想用我自己的一些方法收集字典。 这个问题分为两个部分:
我将如何实施呢? 我已经在堆栈上阅读了使用collection.MutableSequence
或list等对此建议的各种答案。
class OrderedSetOfDictionaries(<something>): def __init__(self, **kwargs): <maybe super().__init__()> <do I have to redefine methods if I do not wish to change their behavior>
所需数据结构的示例
ordered_set_of_dictionaries =
{
"dictionary_1" : {
"key_1": value_1,
"key_2": value_2,
<etc>
},
"dictionary_2" : {
"key_1": value_1,
"key_2": value_2,
<etc>
},
"dictionary_3" : {
"key_1": value_1,
"key_2": value_2,
<etc>
},
<etc>
}
ordered_set_of_dictionaries.last()
-> <dictionary_n>
ordered_set_of_dictionaries["dictionary_1"]["key_1"]
-> value_1
等等
这是通过将OrderedDict子类化的一种方法。 除了last()
函数,我还添加了first()
和ith(i)
函数。 ith(i)
操作类似于列表索引。
from collections import OrderedDict
class ord_dict_with_indexing(OrderedDict):
def __init__(self, *args):
super(ord_dict_with_indexing, self).__init__(*args)
def ith(self, i):
return self.__getitem__(list(self.keys())[i])
def last(self):
return self.ith(-1)
def first(self):
return self.ith(0)
例如:
d = ord_dict_with_indexing()
d["dictionary_1"] = {"key_1":"value_1","key_2":"value_2"}
d["dictionary_2"] = {"key_3":"value_3","key_4":"value_4"}
d["dictionary_3"] = {"key_5":"value_1","key_2":"value_5"}
>>> d.first()
{'key_1': 'value_1', 'key_2': 'value_2'}
>>> d.last()
{'key_2': 'value_5', 'key_5': 'value_1'}
>>> d.ith(1)
{'key_3': 'value_3', 'key_4': 'value_4'}
>>> d['dictionary_1']['key_1']
'value_1'
请注意,该顺序将按照添加元素的顺序出现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.