From e41ea451c1cbe37585ccafdae6f2275a8d70e421 Mon Sep 17 00:00:00 2001
From: Gisle Aas <gisle@aas.no>
Date: Mon, 22 Feb 2010 11:25:57 -0500
Subject: [PATCH] Ticket #12820: fix iteration over MergeDict
---
django/utils/datastructures.py | 30 +++++++++++++++++++++---
tests/regressiontests/datastructures/tests.py | 11 +++++++++
2 files changed, 37 insertions(+), 4 deletions(-)
diff --git a/django/utils/datastructures.py b/django/utils/datastructures.py
index d6fc9dc..8c05e7d 100644
a
|
b
|
class MergeDict(object):
|
37 | 37 | return dict_.getlist(key) |
38 | 38 | return [] |
39 | 39 | |
40 | | def items(self): |
41 | | item_list = [] |
| 40 | def iteritems(self): |
| 41 | seen = set() |
42 | 42 | for dict_ in self.dicts: |
43 | | item_list.extend(dict_.items()) |
44 | | return item_list |
| 43 | for item in dict_.items(): |
| 44 | k, v = item |
| 45 | if k in seen: |
| 46 | continue |
| 47 | seen.add(k) |
| 48 | yield item |
| 49 | |
| 50 | def iterkeys(self): |
| 51 | for k, v in self.iteritems(): |
| 52 | yield k |
| 53 | |
| 54 | def itervalues(self): |
| 55 | for k, v in self.iteritems(): |
| 56 | yield v |
| 57 | |
| 58 | def items(self): |
| 59 | return list(self.iteritems()) |
| 60 | |
| 61 | def keys(self): |
| 62 | return list(self.iterkeys()) |
| 63 | |
| 64 | def values(self): |
| 65 | return list(self.itervalues()) |
45 | 66 | |
46 | 67 | def has_key(self, key): |
47 | 68 | for dict_ in self.dicts: |
… |
… |
class MergeDict(object):
|
50 | 71 | return False |
51 | 72 | |
52 | 73 | __contains__ = has_key |
| 74 | __iter__ = iterkeys |
53 | 75 | |
54 | 76 | def copy(self): |
55 | 77 | """Returns a copy of this object.""" |
diff --git a/tests/regressiontests/datastructures/tests.py b/tests/regressiontests/datastructures/tests.py
index b7885e6..a858e24 100644
a
|
b
|
MergeDict can merge MultiValueDicts
|
34 | 34 | >>> mm.getlist('undefined') |
35 | 35 | [] |
36 | 36 | |
| 37 | >>> sorted(mm.keys()) |
| 38 | ['key1', 'key2', 'key4'] |
| 39 | >>> len(mm.values()) |
| 40 | 3 |
| 41 | >>> "value1" in mm.values() |
| 42 | True |
| 43 | >>> sorted(mm.items(), key=lambda k: k[0]) |
| 44 | [('key1', 'value1'), ('key2', 'value3'), ('key4', 'value6')] |
| 45 | >>> [(k,mm.getlist(k)) for k in sorted(mm)] |
| 46 | [('key1', ['value1']), ('key2', ['value2', 'value3']), ('key4', ['value5', 'value6'])] |
| 47 | |
37 | 48 | ### MultiValueDict ########################################################## |
38 | 49 | |
39 | 50 | >>> d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']}) |