0

I know it is easy to implement.

I want a dictionary like class, which takes a list of dictionaries in the constructor.

If you read from this dict by key, the dict-class should check the list of dictionaries and return the first value. If none contains this key KeyError should be thrown like a normal dict.

This dictionary container should be read only for my usage.

guettli
  • 25,042
  • 81
  • 346
  • 663

3 Answers3

3

You seem to be describing collections.ChainMap, which will be in the next version of Python (3.3, expected to go final later this year). For current/earlier versions of Python, you can copy the implementation from the collections source code.

lvc
  • 34,233
  • 10
  • 73
  • 98
  • 2
    Just some seconds after asking, I found a solution in django: MergeDict: https://github.com/django/django/blob/master/django/utils/datastructures.py Nice to know, that ChainMap will be in Python in the future. – guettli May 31 '12 at 10:49
0

Not really answer to the question: what if you just define method that merge all dictionaries into one? Why make new class for it?
How to merge: How to merge two Python dictionaries in a single expression?
Varargs: Can a variable number of arguments be passed to a function?

Community
  • 1
  • 1
popfalushi
  • 1,332
  • 9
  • 15
  • 1
    If this is not really answer, then you should have put this in as a comment to the question, not as an answer! – Ozair Kafray May 31 '12 at 10:36
  • Well, it is not straightforward answer, but it makes required task and, from my point of view, makes it better than additional class. – popfalushi May 31 '12 at 10:38
0

You can easily implement this with this logic.

  1. Iterate over all the dictionaries in the list.
  2. For each dictionary, see if it has the required key by using key in value statement.
  3. If value is found, return the value from the function.
  4. If you have iterated over all dictionaries, and value is not found, Raise KeyError exception.
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175