summaryrefslogtreecommitdiff
path: root/django/utils/datastructures.py
blob: c1cb6193f50e55bcf71d0e61238db145ae59f01f (plain)
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
class MergeDict:
    """
    A simple class for creating new "virtual" dictionaries that actualy look
    up values in more than one dictionary, passed in the constructor.
    """
    def __init__(self, *dicts):
        self.dicts = dicts

    def __getitem__(self, key):
        for dict in self.dicts:
            try:
                return dict[key]
            except KeyError:
                pass
        raise KeyError

    def get(self, key, default):
        try:
            return self[key]
        except KeyError:
            return default

    def getlist(self, key):
        for dict in self.dicts:
            try:
                return dict.getlist(key)
            except KeyError:
                pass
        raise KeyError

    def items(self):
        item_list = []
        for dict in self.dicts:
            item_list.extend(dict.items())
        return item_list

    def has_key(self, key):
        for dict in self.dicts:
            if dict.has_key(key):
                return True
        return False

class MultiValueDictKeyError(KeyError):
    pass

class MultiValueDict:
    """
    A dictionary-like class customized to deal with multiple values for the same key.

    >>> d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']})
    >>> d['name']
    'Simon'
    >>> d.getlist('name')
    ['Adrian', 'Simon']
    >>> d.get('lastname', 'nonexistent')
    'nonexistent'
    >>> d.setlist('lastname', ['Holovaty', 'Willison'])

    This class exists to solve the irritating problem raised by cgi.parse_qs,
    which returns a list for every key, even though most Web forms submit
    single name-value pairs.
    """
    def __init__(self, key_to_list_mapping=None):
        self.data = key_to_list_mapping or {}

    def __repr__(self):
        return repr(self.data)

    def __getitem__(self, key):
        "Returns the data value for this key; raises KeyError if not found"
        if self.data.has_key(key):
            try:
                return self.data[key][-1] # in case of duplicates, use last value ([-1])
            except IndexError:
                return []
        raise MultiValueDictKeyError, "Key '%s' not found in MultiValueDict %s" % (key, self.data)

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

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

    def get(self, key, default):
        "Returns the default value if the requested data doesn't exist"
        try:
            val = self[key]
        except (KeyError, IndexError):
            return default
        if val == []:
            return default
        return val

    def getlist(self, key):
        "Returns an empty list if the requested data doesn't exist"
        try:
            return self.data[key]
        except KeyError:
            return []

    def setlist(self, key, list_):
        self.data[key] = list_

    def appendlist(self, key, item):
        "Appends an item to the internal list associated with key"
        try:
            self.data[key].append(item)
        except KeyError:
            self.data[key] = [item]

    def has_key(self, key):
        return self.data.has_key(key)

    def items(self):
        # we don't just return self.data.items() here, because we want to use
        # self.__getitem__() to access the values as *strings*, not lists
        return [(key, self[key]) for key in self.data.keys()]

    def keys(self):
        return self.data.keys()

    def update(self, other_dict):
        if isinstance(other_dict, MultiValueDict):
            for key, value_list in other_dict.data.items():
                self.data.setdefault(key, []).extend(value_list)
        elif type(other_dict) == type({}):
            for key, value in other_dict.items():
                self.data.setdefault(key, []).append(value)
        else:
            raise ValueError, "MultiValueDict.update() takes either a MultiValueDict or dictionary"

    def copy(self):
        "Returns a copy of this object"
        import copy
        cp = copy.deepcopy(self)
        return cp

class DotExpandedDict(dict):
    """
    A special dictionary constructor that takes a dictionary in which the keys
    may contain dots to specify inner dictionaries. It's confusing, but this
    example should make sense.

    >>> d = DotExpandedDict({'person.1.firstname': ['Simon'],
            'person.1.lastname': ['Willison'],
            'person.2.firstname': ['Adrian'],
            'person.2.lastname': ['Holovaty']})
    >>> d
    {'person': {'1': {'lastname': ['Willison'], 'firstname': ['Simon']},
    '2': {'lastname': ['Holovaty'], 'firstname': ['Adrian']}}}
    >>> d['person']
    {'1': {'firstname': ['Simon'], 'lastname': ['Willison'],
    '2': {'firstname': ['Adrian'], 'lastname': ['Holovaty']}
    >>> d['person']['1']
    {'firstname': ['Simon'], 'lastname': ['Willison']}

    # Gotcha: Results are unpredictable if the dots are "uneven":
    >>> DotExpandedDict({'c.1': 2, 'c.2': 3, 'c': 1})
    >>> {'c': 1}
    """
    def __init__(self, key_to_list_mapping):
        for k, v in key_to_list_mapping.items():
            current = self
            bits = k.split('.')
            for bit in bits[:-1]:
                current = current.setdefault(bit, {})
            # Now assign value to current position
            try:
                current[bits[-1]] = v
            except TypeError: # Special-case if current isn't a dict.
                current = {bits[-1]: v}