File: orderedmultidict.py

package info (click to toggle)
python-orderedmultidict 1.0.1-1.1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 308 kB
  • sloc: python: 1,305; makefile: 2
file content (838 lines) | stat: -rw-r--r-- 29,715 bytes parent folder | download
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
# -*- coding: utf-8 -*-

#
# omdict - Ordered Multivalue Dictionary.
#
# Ansgar Grunseid
# grunseid.com
# grunseid@gmail.com
#
# License: Build Amazing Things (Unlicense)
#

from __future__ import absolute_import

import sys
from itertools import chain

from itertools import zip_longest

from .itemlist import itemlist

# There's no typing module until 3.5
if sys.version_info >= (3, 5):
    from typing import Iterable, Tuple, Any, List, Dict

from collections.abc import MutableMapping

try:
    # Python 2.7 and later.
    from collections import OrderedDict as odict  # type: ignore
except ImportError:
    # Python 2.6 and earlier.
    from ordereddict import OrderedDict as odict  # type: ignore


_absent = object()  # Marker that means no parameter was provided.
_items_attr = 'items' if sys.version_info[0] >= 3 else 'iteritems'


def callable_attr(obj, attr):
    return hasattr(obj, attr) and callable(getattr(obj, attr))


#
# TODO(grun): Create a subclass of list that values(), getlist(), allitems(),
# etc return that the user can manipulate directly to control the omdict()
# object.
#
# For example, users should be able to do things like
#
#   omd = omdict([(1,1), (1,11)])
#   omd.values(1).append('sup')
#   omd.allitems() == [(1,1), (1,11), (1,'sup')]
#   omd.values(1).remove(11)
#   omd.allitems() == [(1,1), (1,'sup')]
#   omd.values(1).extend(['two', 'more'])
#   omd.allitems() == [(1,1), (1,'sup'), (1,'two'), (1,'more')]
#
# or
#
#   omd = omdict([(1,1), (1,11)])
#   omd.allitems().extend([(2,2), (2,22)])
#   omd.allitems() == [(1,1), (1,11), (2,2), (2,22)])
#
# or
#
#   omd = omdict()
#   omd.values(1) = [1, 11]
#   omd.allitems() == [(1,1), (1,11)]
#   omd.values(1) = list(map(lambda i: i * -10, omd.values(1)))
#   omd.allitems() == [(1,-10), (1,-110)]
#   omd.allitems() = filter(lambda (k,v): v > -100, omd.allitems())
#   omd.allitems() == [(1,-10)]
#
# etc.
#
# To accomplish this, subclass list in such a manner that each list element is
# really a two tuple, where the first tuple value is the actual value and the
# second tuple value is a reference to the itemlist node for that value. Users
# only interact with the first tuple values, the actual values, but behind the
# scenes when an element is modified, deleted, inserted, etc, the according
# itemlist nodes are modified, deleted, inserted, etc accordingly. In this
# manner, users can manipulate omdict objects directly through direct list
# manipulation.
#
# Once accomplished, some methods become redundant and should be removed in
# favor of the more intuitive direct value list manipulation. Such redundant
# methods include getlist() (removed in favor of values()?), addlist(), and
# setlist().
#
# With the removal of many of the 'list' methods, think about renaming all
# remaining 'list' methods to 'values' methods, like poplist() -> popvalues(),
# poplistitem() -> popvaluesitem(), etc. This would be an easy switch for most
# methods, but wouldn't fit others so well. For example, iterlists() would
# become itervalues(), a name extremely similar to iterallvalues() but quite
# different in function.
#


class omdict(MutableMapping):

    """
    Ordered Multivalue Dictionary.

    A multivalue dictionary is a dictionary that can store multiple values per
    key. An ordered multivalue dictionary is a multivalue dictionary that
    retains the order of insertions and deletions.

    Internally, items are stored in a doubly linked list, self._items. A
    dictionary, self._map, is also maintained and stores an ordered list of
    linked list node references, one for each value associated with that key.

    Standard dict methods interact with the first value associated with a given
    key. This means that omdict retains method parity with dict, and a dict
    object can be replaced with an omdict object and all interaction will
    behave identically. All dict methods that retain parity with omdict are:

      get(), setdefault(), pop(), popitem(),
      clear(), copy(), update(), fromkeys(), len()
      __getitem__(), __setitem__(), __delitem__(), __contains__(),
      items(), keys(), values(), iteritems(), iterkeys(), itervalues(),

    Optional parameters have been added to some dict methods, but because the
    added parameters are optional, existing use remains unaffected. An optional
    <key> parameter has been added to these methods:

      items(), values(), iteritems(), itervalues()

    New methods have also been added to omdict. Methods with 'list' in their
    name interact with lists of values, and methods with 'all' in their name
    interact with all items in the dictionary, including multiple items with
    the same key.

    The new omdict methods are:

      load(), size(), reverse(),
      getlist(), add(), addlist(), set(), setlist(), setdefaultlist(),
      poplist(), popvalue(), popvalues(), popitem(), poplistitem(),
      allitems(), allkeys(), allvalues(), lists(), listitems(),
      iterallitems(), iterallkeys(), iterallvalues(), iterlists(),
        iterlistitems()

    Explanations and examples of the new methods above can be found in the
    function comments below and online at

      https://github.com/gruns/orderedmultidict

    Additional omdict information and documentation can also be found at the
    above url.
    """

    def __init__(self, *args, **kwargs):
        # Doubly linked list of itemnodes. Each itemnode stores a key:value
        # item.
        self._items = itemlist()

        # Ordered dictionary of keys and itemnode references. Each itemnode
        # reference points to one of that keys values.
        self._map = odict()

        self.load(*args, **kwargs)

    def load(self, *args, **kwargs):
        """
        Clear all existing key:value items and import all key:value items from
        <mapping>. If multiple values exist for the same key in <mapping>, they
        are all be imported.

        Example:
          omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
          omd.load([(4,4), (4,44), (5,5)])
          omd.allitems() == [(4,4), (4,44), (5,5)]

        Returns: <self>.
        """
        self.clear()
        self.updateall(*args, **kwargs)
        return self

    def copy(self):
        return self.__class__(self.allitems())

    def clear(self):
        self._map.clear()
        self._items.clear()

    def size(self):
        """
        Example:
          omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
          omd.size() == 5

        Returns: Total number of items, including multiple items with the same
        key.
        """
        return len(self._items)

    @classmethod
    def fromkeys(cls, iterable, value=None):
        return cls([(key, value) for key in iterable])

    def has_key(self, key):
        return key in self

    def update(self, *args, **kwargs):
        self._update_updateall(True, *args, **kwargs)

    def updateall(self, *args, **kwargs):
        """
        Update this dictionary with the items from <mapping>, replacing
        existing key:value items with shared keys before adding new key:value
        items.

        Example:
          omd = omdict([(1,1), (2,2)])
          omd.updateall([(2,'two'), (1,'one'), (2,222), (1,111)])
          omd.allitems() == [(1, 'one'), (2, 'two'), (2, 222), (1, 111)]

        Returns: <self>.
        """
        self._update_updateall(False, *args, **kwargs)
        return self

    def _update_updateall(self, replace_at_most_one, *args, **kwargs):
        # Bin the items in <args> and <kwargs> into <replacements> or
        # <leftovers>. Items in <replacements> are new values to replace old
        # values for a given key, and items in <leftovers> are new items to be
        # added.
        replacements, leftovers = dict(), []  # type: Tuple[Dict, List]
        for mapping in chain(args, [kwargs]):
            self._bin_update_items(
                self._items_iterator(mapping), replace_at_most_one,
                replacements, leftovers)

        # First, replace existing values for each key.
        for key, values in replacements.items():
            self.setlist(key, values)
        # Then, add the leftover items to the end of the list of all items.
        for key, value in leftovers:
            self.add(key, value)

    def _bin_update_items(self, items, replace_at_most_one,
                          replacements, leftovers):
        """
        <replacements and <leftovers> are modified directly, ala pass by
        reference.
        """
        for key, value in items:
            # If there are existing items with key <key> that have yet to be
            # marked for replacement, mark that item's value to be replaced by
            # <value> by appending it to <replacements>.
            if key in self and key not in replacements:
                replacements[key] = [value]
            elif (key in self and not replace_at_most_one and
                  len(replacements[key]) < len(self.values(key))):
                replacements[key].append(value)
            else:
                if replace_at_most_one:
                    replacements[key] = [value]
                else:
                    leftovers.append((key, value))

    def _items_iterator(self, container):
        cont = container
        iterator = iter(cont)
        if callable_attr(cont, 'iterallitems'):
            iterator = cont.iterallitems()
        elif callable_attr(cont, 'allitems'):
            iterator = iter(cont.allitems())
        elif callable_attr(cont, 'iteritems'):
            iterator = cont.iteritems()
        elif callable_attr(cont, 'items'):
            iterator = iter(cont.items())
        return iterator

    def get(self, key, default=None):
        if key in self:
            return self._map[key][0].value
        return default

    def getlist(self, key, default=[]):
        """
        Returns: The list of values for <key> if <key> is in the dictionary,
        else <default>. If <default> is not provided, an empty list is
        returned.
        """
        if key in self:
            return [node.value for node in self._map[key]]
        return default

    def setdefault(self, key, default=None):
        if key in self:
            return self[key]
        self.add(key, default)
        return default

    def setdefaultlist(self, key, defaultlist=[None]):
        """
        Similar to setdefault() except <defaultlist> is a list of values to set
        for <key>. If <key> already exists, its existing list of values is
        returned.

        If <key> isn't a key and <defaultlist> is an empty list, [], no values
        are added for <key> and <key> will not be added as a key.

        Returns: List of <key>'s values if <key> exists in the dictionary,
        otherwise <default>.
        """
        if key in self:
            return self.getlist(key)
        self.addlist(key, defaultlist)
        return defaultlist

    def add(self, key, value=None):
        """
        Add <value> to the list of values for <key>. If <key> is not in the
        dictionary, then <value> is added as the sole value for <key>.

        Example:
          omd = omdict()
          omd.add(1, 1)  # omd.allitems() == [(1,1)]
          omd.add(1, 11) # omd.allitems() == [(1,1), (1,11)]
          omd.add(2, 2)  # omd.allitems() == [(1,1), (1,11), (2,2)]

        Returns: <self>.
        """
        self._map.setdefault(key, [])
        node = self._items.append(key, value)
        self._map[key].append(node)
        return self

    def addlist(self, key, valuelist=[]):
        """
        Add the values in <valuelist> to the list of values for <key>. If <key>
        is not in the dictionary, the values in <valuelist> become the values
        for <key>.

        Example:
          omd = omdict([(1,1)])
          omd.addlist(1, [11, 111])
          omd.allitems() == [(1, 1), (1, 11), (1, 111)]
          omd.addlist(2, [2])
          omd.allitems() == [(1, 1), (1, 11), (1, 111), (2, 2)]

        Returns: <self>.
        """
        for value in valuelist:
            self.add(key, value)
        return self

    def set(self, key, value=None):
        """
        Sets <key>'s value to <value>. Identical in function to __setitem__().

        Returns: <self>.
        """
        self[key] = value
        return self

    def setlist(self, key, values):
        """
        Sets <key>'s list of values to <values>. Existing items with key <key>
        are first replaced with new values from <values>. Any remaining old
        items that haven't been replaced with new values are deleted, and any
        new values from <values> that don't have corresponding items with <key>
        to replace are appended to the end of the list of all items.

        If values is an empty list, [], <key> is deleted, equivalent in action
        to del self[<key>].

        Example:
          omd = omdict([(1,1), (2,2)])
          omd.setlist(1, [11, 111])
          omd.allitems() == [(1,11), (2,2), (1,111)]

          omd = omdict([(1,1), (1,11), (2,2), (1,111)])
          omd.setlist(1, [None])
          omd.allitems() == [(1,None), (2,2)]

          omd = omdict([(1,1), (1,11), (2,2), (1,111)])
          omd.setlist(1, [])
          omd.allitems() == [(2,2)]

        Returns: <self>.
        """
        if not values and key in self:
            self.pop(key)
        else:
            it = zip_longest(
                list(self._map.get(key, [])), values, fillvalue=_absent)
            for node, value in it:
                if node is not _absent and value is not _absent:
                    node.value = value
                elif node is _absent:
                    self.add(key, value)
                elif value is _absent:
                    self._map[key].remove(node)
                    self._items.removenode(node)
        return self

    def removevalues(self, key, values):
        """
        Removes all <values> from the values of <key>. If <key> has no
        remaining values after removevalues(), the key is popped.

        Example:
          omd = omdict([(1, 1), (1, 11), (1, 1), (1, 111)])
          omd.removevalues(1, [1, 111])
          omd.allitems() == [(1, 11)]

        Returns: <self>.
        """
        self.setlist(key, [v for v in self.getlist(key) if v not in values])
        return self

    def pop(self, key, default=_absent):
        if key in self:
            return self.poplist(key)[0]
        elif key not in self._map and default is not _absent:
            return default
        raise KeyError(key)

    def poplist(self, key, default=_absent):
        """
        If <key> is in the dictionary, pop it and return its list of values. If
        <key> is not in the dictionary, return <default>. KeyError is raised if
        <default> is not provided and <key> is not in the dictionary.

        Example:
          omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
          omd.poplist(1) == [1, 11, 111]
          omd.allitems() == [(2,2), (3,3)]
          omd.poplist(2) == [2]
          omd.allitems() == [(3,3)]

        Raises: KeyError if <key> isn't in the dictionary and <default> isn't
          provided.
        Returns: List of <key>'s values.
        """
        if key in self:
            values = self.getlist(key)
            del self._map[key]
            for node, nodekey, nodevalue in self._items:
                if nodekey == key:
                    self._items.removenode(node)
            return values
        elif key not in self._map and default is not _absent:
            return default
        raise KeyError(key)

    def popvalue(self, key, value=_absent, default=_absent, last=True):
        """
        If <value> is provided, pops the first or last (key,value) item in the
        dictionary if <key> is in the dictionary.

        If <value> is not provided, pops the first or last value for <key> if
        <key> is in the dictionary.

        If <key> no longer has any values after a popvalue() call, <key> is
        removed from the dictionary. If <key> isn't in the dictionary and
        <default> was provided, return default. KeyError is raised if <default>
        is not provided and <key> is not in the dictionary. ValueError is
        raised if <value> is provided but isn't a value for <key>.

        Example:
          omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3), (2,22)])
          omd.popvalue(1) == 111
          omd.allitems() == [(1,11), (1,111), (2,2), (3,3), (2,22)]
          omd.popvalue(1, last=False) == 1
          omd.allitems() == [(1,11), (2,2), (3,3), (2,22)]
          omd.popvalue(2, 2) == 2
          omd.allitems() == [(1,11), (3,3), (2,22)]
          omd.popvalue(1, 11) == 11
          omd.allitems() == [(3,3), (2,22)]
          omd.popvalue('not a key', default='sup') == 'sup'

        Params:
          last: Boolean whether to return <key>'s first value (<last> is False)
            or last value (<last> is True).
        Raises:
          KeyError if <key> isn't in the dictionary and <default> isn't
            provided.
          ValueError if <value> isn't a value for <key>.
        Returns: The first or last of <key>'s values.
        """
        def pop_node_with_index(key, index):
            node = self._map[key].pop(index)
            if not self._map[key]:
                del self._map[key]
            self._items.removenode(node)
            return node

        if key in self:
            if value is not _absent:
                if last:
                    pos = self.values(key)[::-1].index(value)
                else:
                    pos = self.values(key).index(value)
                if pos == -1:
                    raise ValueError(value)
                else:
                    index = (len(self.values(key)) - 1 - pos) if last else pos
                    return pop_node_with_index(key, index).value
            else:
                return pop_node_with_index(key, -1 if last else 0).value
        elif key not in self._map and default is not _absent:
            return default
        raise KeyError(key)

    def popitem(self, fromall=False, last=True):
        """
        Pop and return a key:value item.

        If <fromall> is False, items()[0] is popped if <last> is False or
        items()[-1] is popped if <last> is True. All remaining items with the
        same key are removed.

        If <fromall> is True, allitems()[0] is popped if <last> is False or
        allitems()[-1] is popped if <last> is True. Any remaining items with
        the same key remain.

        Example:
          omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
          omd.popitem() == (3,3)
          omd.popitem(fromall=False, last=False) == (1,1)
          omd.popitem(fromall=False, last=False) == (2,2)

          omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
          omd.popitem(fromall=True, last=False) == (1,1)
          omd.popitem(fromall=True, last=False) == (1,11)
          omd.popitem(fromall=True, last=True) == (3,3)
          omd.popitem(fromall=True, last=False) == (1,111)

        Params:
          fromall: Whether to pop an item from items() (<fromall> is True) or
            allitems() (<fromall> is False).
          last: Boolean whether to pop the first item or last item of items()
            or allitems().
        Raises: KeyError if the dictionary is empty.
        Returns: The first or last item from item() or allitem().
        """
        if not self._items:
            raise KeyError('popitem(): %s is empty' % self.__class__.__name__)

        if fromall:
            node = self._items[-1 if last else 0]
            key = node.key
            return key, self.popvalue(key, last=last)
        else:
            key = list(self._map.keys())[-1 if last else 0]
            return key, self.pop(key)

    def poplistitem(self, last=True):
        """
        Pop and return a key:valuelist item comprised of a key and that key's
        list of values. If <last> is False, a key:valuelist item comprised of
        keys()[0] and its list of values is popped and returned. If <last> is
        True, a key:valuelist item comprised of keys()[-1] and its list of
        values is popped and returned.

        Example:
          omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
          omd.poplistitem(last=True) == (3,[3])
          omd.poplistitem(last=False) == (1,[1,11,111])

        Params:
          last: Boolean whether to pop the first or last key and its associated
            list of values.
        Raises: KeyError if the dictionary is empty.
        Returns: A two-tuple comprised of the first or last key and its
          associated list of values.
        """
        if not self._items:
            s = 'poplistitem(): %s is empty' % self.__class__.__name__
            raise KeyError(s)

        key = self.keys()[-1 if last else 0]
        return key, self.poplist(key)

    def items(self, key=_absent):
        """
        Raises: KeyError if <key> is provided and not in the dictionary.
        Returns: List created from iteritems(<key>). Only items with key <key>
          are returned if <key> is provided and is a dictionary key.
        """
        return list(self.iteritems(key))

    def keys(self):
        return list(self.iterkeys())

    def values(self, key=_absent):
        """
        Raises: KeyError if <key> is provided and not in the dictionary.
        Returns: List created from itervalues(<key>).If <key> is provided and
          is a dictionary key, only values of items with key <key> are
          returned.
        """
        if key is not _absent and key in self._map:
            return self.getlist(key)
        return list(self.itervalues())

    def lists(self):
        """
        Returns: List created from iterlists().
        """
        return list(self.iterlists())

    def listitems(self):
        """
        Returns: List created from iterlistitems().
        """
        return list(self.iterlistitems())

    def iteritems(self, key=_absent):
        """
        Parity with dict.iteritems() except the optional <key> parameter has
        been added. If <key> is provided, only items with the provided key are
        iterated over. KeyError is raised if <key> is provided and not in the
        dictionary.

        Example:
          omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
          omd.iteritems(1) -> (1,1) -> (1,11) -> (1,111)
          omd.iteritems() -> (1,1) -> (2,2) -> (3,3)

        Raises: KeyError if <key> is provided and not in the dictionary.
        Returns: An iterator over the items() of the dictionary, or only items
          with the key <key> if <key> is provided.
        """
        if key is not _absent:
            if key in self:
                items = [
                    (node.key, node.value) for node in self._map[key]
                ]  # type: Iterable[Tuple[Any, Any]]
                return iter(items)
            raise KeyError(key)
        items = self._map.items()
        return iter((key, nodes[0].value) for (key, nodes) in items)

    def iterkeys(self):
        return iter(self._map.keys())

    def itervalues(self, key=_absent):
        """
        Parity with dict.itervalues() except the optional <key> parameter has
        been added. If <key> is provided, only values from items with the
        provided key are iterated over. KeyError is raised if <key> is provided
        and not in the dictionary.

        Example:
          omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
          omd.itervalues(1) -> 1 -> 11 -> 111
          omd.itervalues() -> 1 -> 11 -> 111 -> 2 -> 3

        Raises: KeyError if <key> is provided and isn't in the dictionary.
        Returns: An iterator over the values() of the dictionary, or only the
          values of key <key> if <key> is provided.
        """
        if key is not _absent:
            if key in self:
                return iter([node.value for node in self._map[key]])
            raise KeyError(key)
        return iter([nodes[0].value for nodes in self._map.values()])

    def allitems(self, key=_absent):
        '''
        Raises: KeyError if <key> is provided and not in the dictionary.
        Returns: List created from iterallitems(<key>).
        '''
        return list(self.iterallitems(key))

    def allkeys(self):
        '''
        Example:
          omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
          omd.allkeys() == [1,1,1,2,3]

        Returns: List created from iterallkeys().
        '''
        return list(self.iterallkeys())

    def allvalues(self, key=_absent):
        '''
        Example:
          omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
          omd.allvalues() == [1,11,111,2,3]
          omd.allvalues(1) == [1,11,111]

        Raises: KeyError if <key> is provided and not in the dictionary.
        Returns: List created from iterallvalues(<key>).
        '''
        return list(self.iterallvalues(key))

    def iterallitems(self, key=_absent):
        '''
        Example:
          omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
          omd.iterallitems() == (1,1) -> (1,11) -> (1,111) -> (2,2) -> (3,3)
          omd.iterallitems(1) == (1,1) -> (1,11) -> (1,111)

        Raises: KeyError if <key> is provided and not in the dictionary.
        Returns: An iterator over every item in the diciontary. If <key> is
          provided, only items with the key <key> are iterated over.
        '''
        if key is not _absent:
            # Raises KeyError if <key> is not in self._map.
            return self.iteritems(key)
        return self._items.iteritems()

    def iterallkeys(self):
        '''
        Example:
          omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
          omd.iterallkeys() == 1 -> 1 -> 1 -> 2 -> 3

        Returns: An iterator over the keys of every item in the dictionary.
        '''
        return self._items.iterkeys()

    def iterallvalues(self, key=_absent):
        '''
        Example:
          omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
          omd.iterallvalues() == 1 -> 11 -> 111 -> 2 -> 3

        Returns: An iterator over the values of every item in the dictionary.
        '''
        if key is not _absent:
            if key in self:
                return iter(self.getlist(key))
            raise KeyError(key)
        return self._items.itervalues()

    def iterlists(self):
        '''
        Example:
          omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
          omd.iterlists() -> [1,11,111] -> [2] -> [3]

        Returns: An iterator over the list comprised of the lists of values for
        each key.
        '''
        return map(lambda key: self.getlist(key), self)

    def iterlistitems(self):
        """
        Example:
          omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
          omd.iterlistitems() -> (1,[1,11,111]) -> (2,[2]) -> (3,[3])

        Returns: An iterator over the list of key:valuelist items.
        """
        return map(lambda key: (key, self.getlist(key)), self)

    def reverse(self):
        """
        Reverse the order of all items in the dictionary.

        Example:
          omd = omdict([(1,1), (1,11), (1,111), (2,2), (3,3)])
          omd.reverse()
          omd.allitems() == [(3,3), (2,2), (1,111), (1,11), (1,1)]

        Returns: <self>.
        """
        for key in self._map.keys():
            self._map[key].reverse()
        self._items.reverse()
        return self

    def __eq__(self, other):
        if callable_attr(other, 'iterallitems'):
            myiter, otheriter = self.iterallitems(), other.iterallitems()
            for i1, i2 in zip_longest(myiter, otheriter, fillvalue=_absent):
                if i1 != i2 or i1 is _absent or i2 is _absent:
                    return False
        elif not hasattr(other, '__len__') or not hasattr(other, _items_attr):
            return False
        # Ignore order so we can compare ordered omdicts with unordered dicts.
        else:
            if len(self) != len(other):
                return False
            for key, value in other.items():
                if self.get(key, _absent) != value:
                    return False
        return True

    def __ne__(self, other):
        return not self.__eq__(other)

    def __len__(self):
        return len(self._map)

    def __iter__(self):
        for key in self.iterkeys():
            yield key

    def __contains__(self, key):
        return key in self._map

    def __getitem__(self, key):
        if key in self:
            return self.get(key)
        raise KeyError(key)

    def __setitem__(self, key, value):
        self.setlist(key, [value])

    def __delitem__(self, key):
        return self.pop(key)

    def __nonzero__(self):
        return bool(self._map)

    def __str__(self):
        return '{%s}' % ', '.join(
            map(lambda p: '%r: %r' % (p[0], p[1]), self.iterallitems()))

    def __repr__(self):
        return '%s(%s)' % (self.__class__.__name__, self.allitems())

    def __or__(self, other):
        return self.__class__(chain(_get_items(self), _get_items(other)))

    def __ior__(self, other):
        for k, v in _get_items(other):
            self.add(k, value=v)
        return self


def _get_items(mapping):
    """Find item iterator for an object."""
    names = ('iterallitems', 'allitems', 'iteritems', 'items')
    exist = (n for n in names if callable_attr(mapping, n))
    for a in exist:
        return getattr(mapping, a)()
    raise TypeError(
        "Object {} has no compatible items interface.".format(mapping))