当前位置: 动力学知识库 > 问答 > 编程问答 >

python - adding values to default dict list of values

问题描述:

Python Question:

I have a default dict/dict , say a[1] = (1,2,3) such that a[1][0] = 1 and so on.

Now I want to add to the list of values on the same key. Please understand, I don't want to append but add more values in the same list. For example I want to add 5 to the key a[1] but only in the single list hence:

a[1][1].append("5") = (1, [2,5], 3)

Is there something that can help me do this ?

网友答案:

You ask:

Well, I have a dict and I'm trying to add more values to the same key. Is that in any way possible ?

Not directly. A dict always has exactly one value per key. Using a defaultdict doesn't change that.

But the usual way to simulate a dict with multiple values per key (which some languages call a "multidict") is to just use a list of those multiple values as the single value. For example:

>>> d = {'a': [0, 1, 2], 'b': [1, 2, 3]}
>>> d['a'].append(3)
>>> d['a']
>>> [0, 1, 2, 3]

You seem to be using tuples instead of lists. You can do that, but, because tuples are immutable, you can't call append on them; you have to replace them with the new larger tuple. Like this:

>>> d = {'a': (0, 1, 2), 'b': (1, 2, 3)}
>>> d['a'] = d['a'] + (3,)
>>> d['a']
>>> (0, 1, 2, 3)

That makes the code a bit more complicated than if you'd used lists, but it works.

Meanwhile, using a defaultdict is completely irrelevant here. All a defaultdict does is automatically handle the case where the key doesn't exist. For example:

>>> d = {'b': (1, 2, 3)}
>>> d['a'] = d['a'] + (3,)
KeyError: 'a'
>>> d = defaultdict(tuple, {'b': (1, 2, 3)})
>>> d['a'] = d['a'] + (3,)
>>> d
{'b': (1, 2, 3), 'a': (3,)}

Meanwhile, it looks like you're trying to use a structure that normally stores a single value for each key, but can magically convert into multiple values the first time you need to expand it. In the general case, that's ambiguous—there's no way to distinguish between a single value that happens to be a tuple or a list, vs. multiple values. You can do it in a specific case where you know your values will never be collections (but remember that strings are collections of strings; that will bite you at some point…), or may be collections but will never be the specific type of collection you're using, or whatever. But because that's usually not a good idea, Python doesn't make it easy. So, you have to do something like this:

def add_to_multidict(multidict, key, value):
    if key in multidict:
        if isinstance(multidict[key], tuple):
            multidict[key] = multidict[key] + (value,)
        else:
            multidict[key] = (multidict[key], value)
    else:
        multidict[key] = value

If you want to be able to call this as a method on the dict, you will need to subclass dict and write methods to do it. If you want to be able to call it as a method on the value, you need to subclass tuple as well, and make your dict subclass use the tuple subclass.


Finally, it looks like you want to do this not just with the multidict itself, but also with the individual values that the multidict stores—in other words, you want each key to map to a tuple of objects which themselves are either single objects or tuples of objects. You'll need to write the code to push that logic down one more step; it's not that hard.

If you want to push this down an infinite number of steps, so you can do d['a'][1][2][1].append(3), then you will want to do this recursively: the tuple subclass just has to create an instance of itself when expanding a value, rather than creating a tuple.

网友答案:

In Python tuples are immutable, so what you are trying to do will not work.

网友答案:
a[1] = [[1], [2], [3]]

a[1][1].append(5)     # -> [[1], [2, 5], [3]]

It's not clear what you are actually trying to actually do with this; there may very well be a better way to accomplish it.

分享给朋友:
您可能感兴趣的文章:
随机阅读: