Creating dictionaries with predefined keys

In python, is there a way to create a class that is considered a dictionary, but does it have keys predefined when creating a new instance?

+3
source share
5 answers

You can easily expand any built-in type. Here's how you do it with dict:

>>> class MyClass(dict):
...     def __init__(self, *args, **kwargs):
...             self['mykey'] = 'myvalue'
...             self['mykey2'] = 'myvalue2'
...
>>> x = MyClass()
>>> x['mykey']
'myvalue'
>>> x
{'mykey2': 'myvalue2', 'mykey': 'myvalue'}

I have not been able to find the Python documentation that talks about this, but the very popular Dive Into Python book (available free online) has some examples of this.

+8
source

You can also have dict subclasses to restrict keys to a predefined list by overriding __setitem__()

>>> class LimitedDict(dict):
    _keys = "a b c".split()
    def __init__(self, valtype=int):
        for key in LimitedDict._keys:
            self[key] = valtype()
    def __setitem__(self, key, val):
        if key not in LimitedDict._keys:
            raise KeyError
        dict.__setitem__(self, key, val)


>>> limited = LimitedDict()
>>> limited['a']
0
>>> limited['a'] = 3
>>> limited['a']
3
>>> limited['z'] = 0

Traceback (most recent call last):
  File "<pyshell#61>", line 1, in <module>
    limited['z'] = 0
  File "<pyshell#56>", line 8, in __setitem__
    raise KeyError
KeyError
>>> len(limited)
3
+8

, Python dict , :

    class SubDict(dict):
        def __init__(self):
            dict.__init__(self)
            self.update({
                'foo': 'bar',
                'baz': 'spam',})

dict __init__() (, ). __init__ supercalss __init__(), , . SubDictionary .

    subDict = SubDict()
    print subDict    # prints {'foo': 'bar', 'baz': 'spam'}
+3

, , , , , .

perl, ,


grep{$_{$_}++} qw/ a a b c c c /;
print map{$_."\t".$_{$_}."\n"} sort {$_{$b}$_{$a}} keys %_;

c   3
a   2
b   1

Python :


l = ["a","a","b","c","c","c"]
d = {}
for item in l:
    d[item] += 1

Traceback (most recent call last):
  File "./y.py", line 6, in 
    d[item] += 1
KeyError: 'a'

defaultdict ,


from collections import defaultdict
from operator import itemgetter

l = ["a","a","b","c","c","c"]
d = defaultdict(int)
for item in l:
    d[item] += 1

dl = sorted(d.items(),key=itemgetter(1), reverse=True)
for item in dl:
    print item

('c', 3)
('a', 2)
('b', 1)
+1

dict init.

class MyClass(dict)

def __init __ (self):
    "" "Creates a new dict with default values" "" "

    self ['key1'] = 'value1'

Remember that in python, any class that "acts like a dict" is usually treated as one, so you don't have to worry too much about being a subclass, you can implement the dict methods instead, although the above approach is probably more useful for you:).

0
source

Source: https://habr.com/ru/post/1707562/


All Articles