Welcome, guest | Sign In | My Account | Store | Cart

This implements two types of dictionary-like objects where there can be more than one entry with the same key. One is OrderedMultiDict, which preserves the order of all entries across all keys. The other is UnorderedMultidict, which only preserves the order of entries for the same key.

Download MultiDict.py Example:

>>> import MultiDict
>>> od = MultiDict.OrderedMultiDict()
>>> od["Name"] = "Andrew"; od["Color"] = "Green"
>>> od["Name"] = "Karen"; od["Color"] = "Brown"
>>> od["Name"]
'Karen'
>>> od.getall("Name")
['Andrew', 'Karen']
>>> for k, v in od.allitems():
...     print "%r == %r", (k, v)
...
'Name' == 'Andrew'
'Color' == 'Green'
'Name' == 'Karen'
'Color' == 'Brown'
>>> ud = MultDict.UnorderedMultiDict(od)
>>> for k, v in ud.allitems():
...     print "%r == %r", (k, v)
...
'Name' == 'Andrew'
'Name' == 'Karen'
'Color' == 'Green'
'Color' == 'Brown'
>>>
Python, 235 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
# Written in 2003 by Andrew Dalke, Dalke Scientific Software, LLC.
# This software has been released to the public domain.  No
# copyright is asserted.

from __future__ import generators

# Implementation inheritence -- not asserting a class hierarchy here
#
# If there is a class hierarchy, OrderedMultiDict is a child of
# UnorderedMultiDict because it makes stronger but not different
# guarantees on how the data works, at least data-wise.
# Performance-wise, Ordered has a slower (O(n)) than Unordered (O(1)).
# Convince me otherwise and I'll change.  Besides, hierarchies are
# overrated.
class _BaseMultiDict:
    def __str__(self):
        """shows contents as if this is a dictionary

        If multiple values exist for a given key, use the last
        one added.
        """
        d = {}
        for k in self.data:
            d[k] = self.data[k][-1]
        return str(d)
    def __len__(self):
        """the number of unique keys"""
        return len(self.data)

    def __getitem__(self, key):
        """value for a given key

        If more than one value exists for the key, use one added most recently
        """
        return self.data[key][-1]

    def get(self, key, default = None):
        """value for the given key; default = None if not present
        
        If more than one value exists for the key, use the one added
        most recently.
        """
        return self.data.get(key, [default])[-1]
    
    def __contains__(self, key):
        """check if the key exists"""
        return key in self.data

    def keys(self):
        """unordered list of unique keys"""
        return self.data.keys()

    def values(self):
        """unordered list of values

        If more than one value exists for a given key, use the value
        added most recently.
        """
        return [x[-1] for x in self.data.values()]
    
    def items(self):
        """unordered list of key/value pairs

        If more than one value exists for a given key, use the value
        added most recently.
        """
        return [(k, v[-1]) for k, v in self.data.items()]

    def getall(self, key):
        """Get all values for a given key

        Multiple values are returned in input order.
        If the key does not exists, returns an empty list.
        """
        return self.data[key]

    def __iter__(self):
        """iterate through the list of unique keys"""
        return iter(self.data)

    
class OrderedMultiDict(_BaseMultiDict):
    """Store key/value mappings.

    Acts like a standard dictionary with the following features:
       - duplicate keys are allowed;

       - input order is preserved for all key/value pairs.

    >>> od = OrderedMultiDict([("Food", "Spam"), ("Color", "Blue"),
    ...                        ("Food", "Eggs"), ("Color", "Green")])
    >>> od["Food"]
    'Eggs'
    >>> od.getall("Food")
    ['Spam', 'Eggs']
    >>> list(od.allkeys())
    ['Food', 'Color', 'Food', 'Color']
    >>>

    The order of keys and values(eg, od.allkeys() and od.allitems())
    preserves input order.

    Can also pass in an object to the constructor which has an
    allitems() method that returns a list of key/value pairs.

    """
    def __init__(self, multidict = None):
        self.data = {}
        self.order_data = []
        if multidict is not None:
            if hasattr(multidict, "allitems"):
                multidict = multidict.allitems()
            for k, v in multidict:
                self[k] = v
    def __eq__(self, other):
        """Does this OrderedMultiDict have the same contents and order as another?"""
        return self.order_data == other.order_data
    def __ne__(self, other):
        """Does this OrderedMultiDict have different contents or order as another?"""
        return self.order_data != other.order_data
    
    def __repr__(self):
        return "<OrderedMultiDict %s>" % (self.order_data,)

    def __setitem__(self, key, value):
        """Add a new key/value pair

        If the key already exists, replaces the existing value
        so that d[key] is the new value and not the old one.

        To get all values for a given key, use d.getall(key).
        """
        self.order_data.append((key, value))
        self.data.setdefault(key, []).append(value)

    def __delitem__(self, key):
        """Remove all values for the given key"""
        del self.data[key]
        self.order_data[:] = [x for x in self.order_data if x[0] != key]

    def allkeys(self):
        """iterate over all keys in input order"""
        for x in self.order_data:
            yield x[0]
    def allvalues(self):
        """iterate over all values in input order"""
        for x in self.order_data:
            yield x[1]
    def allitems(self):
        """iterate over all key/value pairs in input order"""
        return iter(self.order_data)


    
class UnorderedMultiDict(_BaseMultiDict):
    """Store key/value mappings.

    Acts like a standard dictionary with the following features:
       - duplicate keys are allowed;

       - input order is preserved for all values of a given
           key but not between different keys.

    >>> ud = UnorderedMultiDict([("Food", "Spam"), ("Color", "Blue"),
    ...                          ("Food", "Eggs"), ("Color", "Green")])
    >>> ud["Food"]
    'Eggs'
    >>> ud.getall("Food")
    ['Spam', 'Eggs']
    >>>

    The order of values from a given key (as from ud.getall("Food"))
    is guaranteed but the order between keys (as from od.allkeys()
    and od.allitems()) is not.

    Can also pass in an object to the constructor which has an
    allitems() method that returns a list of key/value pairs.

    """
    def __init__(self, multidict = None):
        self.data = {}
        if multidict is not None:
            if hasattr(multidict, "allitems"):
                multidict = multidict.allitems()
            for k, v in multidict:
                self[k] = v

    def __eq__(self, other):
        """Does this UnorderedMultiDict have the same keys, with values in the same order, as another?"""
        return self.data == other.data

    def __ne__(self, other):
        """Does this UnorderedMultiDict NOT have the same keys, with values in the same order, as another?"""
        return self.data != other.data

    def __repr__(self):
        return "<UnorderedMultiDict %s>" % (self.data,)

    def __setitem__(self, key, value):
        """Add a new key/value pair

        If the key already exists, replaces the existing value
        so that d[key] is the new value and not the old one.

        To get all values for a given key, use d.getall(key).
        """
        self.data.setdefault(key, []).append(value)

    def __delitem__(self, key):
        """Remove all values for the given key"""
        del self.data[key]

    def allkeys(self):
        """iterate over all keys in arbitrary order"""
        for k, v in self.data.iteritems():
            for x in v:
                yield k

    def allvalues(self):
        """iterate over all values in arbitrary order"""
        for v in self.data.itervalues():
            for x in v:
                yield x

    def allitems(self):
        """iterate over all key/value pairs, in arbitrary order

        Actually, the keys are iterated in arbitrary order but all
        values for that key are iterated at sequence of addition
        to the UnorderedMultiDict.

        """
        for k, v in self.data.iteritems():
            for x in v:
                yield (k, x)

The latest version of this code can be found at http://www.dalkescientific.com/Python/