Python: General way to traverse and replace items in nested sequences?

Status
Not open for further replies.

gloucester

Ars Scholae Palatinae
996
Is there a general way to traverse and replace the items in a nested sequence of arbitrary depth? Say, for instance, that I want to eliminate all the commas in any strings in some absurd nested sequence object, maybe one of which looks something like this:
Code:
{'key1': ['string with, a comma', ['another string with, a comma']], 'key2': ('this one, is in a tuple', \
{'key3': ['that also, has a dictionary in it]}, 'you get, the point'), 'key4': 'I, hope'}

I can do something like this:
Code:
from copy import deepcopy

def kill_commas(container):
    """finds any COMMA lurking in any string anywhere in a standard sequence object,
    including in a nested sequence of sequences of arbitrary depth, and DESTROYS it"""

    copy = deepcopy(container)

    if isinstance(copy, str):
        return copy.replace(',', '')
    else:
        if isinstance(copy, list):
            for i, v in enumerate(copy):
                copy[i] = kill_commas(v)
        elif isinstance(copy, tuple):
            copy = list(copy)
            for i, v in enumerate(copy):
                copy[i] = kill_commas(v)
            copy = tuple(copy)
        elif isinstance(copy, dict):
            for k in copy.keys():
                copy[k] = kill_commas(copy[k])

    return copy
But that only works for the types I've explicitly checked for, and we're always told we're doing something wrong if we're type-checking in Python anyway. I tried coming up with something using __iter__(), but I ran into problems needing to recreate the nested objects, since some sequences are immutable, and there are multiple ways of doing indexing (e.g., dictionaries must be reference by key). There is also more than one iteration protocol in Python—for instance, strings don't use __iter__() at all.

What's the Pythonic way to do this?
 

Alamout

Ars Legatus Legionis
27,285
Gosh, did classes start already? ;)

The main issue you're hitting is that some sequences are immutable and some aren't. But you're returning a copy of your object anyway (note: doing this recursively is going to use a huge amount of memory), so you should just treat lists as immutable and return a new list when you encounter one. Ditto for dictionaries.

But you're not going to get away from the fact that you need to do some type-checking--you'll never figure out when you're at a base-case otherwise. I'm not sure there's a fantastically Pythonic way to do this.

edit: I suggest you check your (ahem) specification to see whether they said sequence or iterable. If it's the former, then you're making a mistaken assumption about your inputs.
 

lostnihilist

Ars Scholae Palatinae
1,436
For type checking, I think I'd use the collections module for checking against the types, and dispatch accordingly. Assuming you are using python 2.X, you'll want to check against basestring, not str.

edit:
wait, obviously this is homework. I'm not giving you the answer!
Hints: 1) if you are returning copies of everything, you don't need to use deepcopy. Since you are going through the entire object recursively, you'll hit all the nodes anyway. 2) you should only need to check 3 types: iterables, basestring, and mappings and use the container's class to generate a copy of itself. 3) generator expressions are your friend.
 

gloucester

Ars Scholae Palatinae
996
lostnihilist, thanks for the tip on the collections module. I will have a look at it. I will also look at generators, as I've never actually tried to use them. (And it's not homework.)

spankalee, how do you mean? Does it matter much whether I make the copies up front or on-the-go, other than in terms of memory consumption?

Alamout":2oodr5ha said:
Gosh, did classes start already? ;)
I'm not a student. I've only ever self-studied programming and CS stuff. It's just a tool for me.

Alamout":2oodr5ha said:
The main issue you're hitting is that some sequences are immutable and some aren't. But you're returning a copy of your object anyway (note: doing this recursively is going to use a huge amount of memory), so you should just treat lists as immutable and return a new list when you encounter one. Ditto for dictionaries.
I know. The problem I was originally trying to solve only contains nested dictionaries and lists, so I was just changing in-place. But I was running into problems figuring out how to do the recursion generally. Say you have lst = [[['finally, a string']]]. You can do something like re-assign lst = [kill_commas(x) for x in lst] in this instance, but then you need another tactic entirely if any of the nested objects are dictionaries. That's struck me as sort of absurd, because the trouble really just comes down to how they're indexed, so long as everything's mutable.

Is recursion simply the wrong approach to begin with? Is there a way easily to measure the "depth" of a nested structure and re-assign in a loop? (Though that doesn't get around the problem of there being sundry ways of indexing containers.)

Alamout":2oodr5ha said:
But you're not going to get away from the fact that you need to do some type-checking--you'll never figure out when you're at a base-case otherwise. I'm not sure there's a fantastically Pythonic way to do this.
Well, setting aside checking the base-case, is there a more general way to dig down into the nested structure without type-checking?

It seems strange that there's a fairly standard iteration protocol but it's difficult to do this even for those types that use it, I guess because indexing, etc., are not standardized. It seems like there should be a standard, say iteritems() method for all iterables that returns a tuple (indexing_value, value) so that you can easily reconstruct any (mutable) iterable by doing container[indexing_value] = do_something_to(value). I guess the closest we can get is putting that in a try clause, and use enumerate(container) in the except clause?

Alamout":2oodr5ha said:
edit: I suggest you check your (ahem) specification to see whether they said sequence or iterable. If it's the former, then you're making a mistaken assumption about your inputs.
Will you remind me of how Python programmers use those terms? The documentation, as I glance at it again, essentially says that a sequence is a string-like object, a tuple, or an xrange object, and that an iterable is anything that has __iter__ to return an iteration object. But tuples and xrange have __iter__, so what makes them sequences? The terminology doesn't hinge on mutability, does it?
 

Alamout

Ars Legatus Legionis
27,285
gloucester":3pw51d06 said:
Alamout":3pw51d06 said:
edit: I suggest you check your (ahem) specification to see whether they said sequence or iterable. If it's the former, then you're making a mistaken assumption about your inputs.
Will you remind me of how Python programmers use those terms? The documentation, as I glance at it again, essentially says that a sequence is a string-like object, a tuple, or an xrange object, and that an iterable is anything that has __iter__ to return an iteration object. But tuples and xrange have __iter__, so what makes them sequences? The terminology doesn't hinge on mutability, does it?
An iterable is an object that can return its values one at a time--the __iter__ method isn't a great definition because strings don't have that (although arguably they should). Whether or not it has an __iter__ method, you can always iterate over an iterable by simply using a for-loop, or by using the iter() built-in function.

A sequence is always an iterable, with the additional quality that it has an order: you can index into a sequence using integers. Dictionaries (and sets) are not sequences, because they don't have an order--a dictionary is allowed to store things however it wants so that it can use an efficient hashing.

So, the reason I was asking about the specification is because if it says sequence then you have a much easier job--you can ignore dictionaries, which are a pain because of the way iteration works on them.

I'm not a student. I've only ever self-studied programming and CS stuff. It's just a tool for me.
Why do you need this tool? The reason I assume this is a homework assignment is a) this is a quintessential recursive-programming homework problem, one that gets you digging into Python at the same time, and b) I can't think of you would ever want to do this in a real application.

To convince me this isn't homework, you need to explain: why do you have a recursive object of lists, dictionaries and tuples of strings, of arbitrary depth, that you need to remove all the commas from? That is a ludicrous problem. No programmer needs to solve that problem, because no one would construct such an object in the first place. It's a good exercise, though.

If it's not a homework problem, the real answer is to figure out how you got in this situation, and stop doing that. ;)
 

gloucester

Ars Scholae Palatinae
996
Alamout, I am not interested in convincing you that this isn't a homework problem. Thank you for your help.

The consensus in this thread seems to be that there simply is not a general way to do this in Python. Indexing works differently for different sorts of iterables (sequences v. non-sequences), so the best you can do is type-check and handle the cases you think you'll run into. That's surprising, since this would be trivial if all iterables had an iteritems method like dictionaries do, or if a function otherwise equivalent to enumerate returned (key, val) for iterables that don't preserve order.
 

lostnihilist

Ars Scholae Palatinae
1,436
I tend to agree that there should be some way to iterate over sequences and mappings in a similar manner, but alas, there is not. You could make your own enumerate function:

Code:
def enum(cont):
    if isinstance(cont, collections.Mapping):
        return cont.iteritems() #.items() for Py3
    else:
        return enumerate(cont)

though you still can't necessarily do in-place replacements due to immutable types as well as (usually lazy) iterables that don't support __setitem__.

Taking you at your word (regarding student status), this is best I can do:

Code:
import collections
import types


def comma_remover(container):
    t = container.__class__
    if isinstance(container, basestring):
        return container.replace(',', '')
    elif isinstance(container, collections.Mapping):
        return t((x,comma_remover(container[x])) for x in container)
    elif isinstance(container, collections.Iterable):
        # Add other non-replicable iterables here. 
        t = tuple if isinstance(t, (types.GeneratorType,)) else t
        return t(comma_remover(x) for x in container)
    else:
        raise ValueError("I don't know how to handle container type: %s" %
                         type(container))

The biggest pitfall is if the container's class's __init__ doesn't accept the given arguments (this is why I check against GeneratorType). It might be more robust to put dict() on the Mapping type, but maybe not.

Code:
>>> l = ['abc,def', {1:'abc,def',2:('1234,456', '789,101112')}, set(['abc,def', 'ifj,klm'])]
>>> m = comma_remover(l)
>>> m
['abcdef', {1: 'abcdef', 2: ('1234456', '789101112')}, set(['ifjklm', 'abcdef'])]
>>> l
['abc,def', {1: 'abc,def', 2: ('1234,456', '789,101112')}, set(['ifj,klm', 'abc,def'])]
>>>
>>> n = list(range(10))
>>> for kidx, val in enum(n): print kidx, val
... 
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
>>> d = dict(zip(range(10), range(1,11)))
>>> for kidx, val in enum(d): print kidx, val
... 
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
 

gloucester

Ars Scholae Palatinae
996
redacted, now that's my kind of solution! This all came up in the context of listening to a JSON data stream. I looked at it and said to myself, you know, that looks basically like Python. So rather than parsing it correctly, I changed the "t" in "true" to "T" and read it in with eval(). ... An ounce of do-the-right-thing instinct would have given me the even easier (and much safer) import json; json.loads(data).

(Back to Alamout's assertion that this problem is ludicrous—is it really ludicrous to want to do something like code a listener that can take any JSON stream, sight-unseen, parse it, then write the values to a database with the correct inferred types? That requires precisely this code because the data might have numbers formatted as strings with commas separating factors of a thousand.)

localnihilist, I like your solution. It's very readable and straightforward, which I guess is as good as it's going to get in the case. And I will start using the collections module, which I was ignorant of.

Anyone want to take a stab at it using multimethod decorators? :D
 

Alamout

Ars Legatus Legionis
27,285
gloucester":id6b14ao said:
(Back to Alamout's assertion that this problem is ludicrous—is it really ludicrous to want to do something like code a listener that can take any JSON stream, sight-unseen, parse it, then write the values to a database with the correct inferred types? That requires precisely this code because the data might have numbers formatted as strings with commas separating factors of a thousand.)
I said no programmer would ever need to solve that problem. Clearly I wasn't talking about Javascript. :D

As you figured out, the best solution for your problem is to use json, which is in fact what I recommended in my own way: figure out how you got in that situation (eval-ing a bunch of text and then trying to process it), and stop doing that (use the library that does exactly what you want, instead).

For kicks, here's a version of this that works on any sequence (and on sets, because of the way iteration works on them):
Code:
def kill_commas(seq):
    def top_kill(s):
        for i in s:
            if isinstance(i, str):
                yield i.replace(',', '')
            else:
                yield type(i)(top_kill(i))

    return type(seq)(top_kill(seq))
I don't think there's a way to avoid that isinstance() call. The str() function doesn't take an iterable, so you can't use it to generate new strings the way you can generate new lists and tuples. At some point you just have to pick a base-case.

I don't deal with generators (unlike lostnihilist) because generators aren't sequences, which means I can save some type-checking there.
 

gloucester

Ars Scholae Palatinae
996
bk0":1ro8ligs said:
Wait, you are taking a raw network stream and passing it directly to eval()? Are you serious?
Since I noted the correct way to do it in my post, it should be obvious that I'm not. But, yes, I did do it initially. And, yes, I know why it's a Very, Very Bad Thing To Do. (Though it's a trusted stream.)

lostnihilist":1ro8ligs said:
but a multimethod approach requires explicitly listing all the accepted types, which I thought you were trying to avoid.
Does it? I was wondering if you could make it work with, e.g., the collections module to get something at least as flexible as your example. I really have no idea, I was just reading about that approach before returning to this thread. ...

Alamout":1ro8ligs said:
I said no programmer would ever need to solve that problem. Clearly I wasn't talking about Javascript. :D
Ha, fair enough. To be clear, I am not trying to do that. I have a few streams to parse, and in doing so I initially counted the depth wrong in doing the replacements. So I thought, this is stupid, why am I not just writing a general recursive function to handle arbitrary depth? Having done that, I thought, well, this looks pretty general, except that it only works on dictionaries and strings. I started trying to figure out how to make it work on a general container, failed, and came here. But it is just curiosity.

Alamout":1ro8ligs said:
As you figured out, the best solution for your problem is to use json, which is in fact what I recommended in my own way: figure out how you got in that situation (eval-ing a bunch of text and then trying to process it), and stop doing that (use the library that does exactly what you want, instead).
Using a proper JSON parser doesn't solve the problem. (Doing eval(data) gives the exact same output as the json.loads(data).) The problem is not how the data are stored and transmitted, but that the numbers are stored as strings. Strings that include commas marking off factors of 1,000. If there are functions in the JSON parser that convert things that look like numbers into numbers, someone had to write code just like this. (Granted, that someone would be someone else.)

Alamout":1ro8ligs said:
For kicks, here's a version of this that works on any sequence (and on sets, because of the way iteration works on them):
Code:
def kill_commas(seq):
    def top_kill(s):
        for i in s:
            if isinstance(i, str):
                yield i.replace(',', '')
            else:
                yield type(i)(top_kill(i))

    return type(seq)(top_kill(seq))
I need to go learn how to use generators. Looking at that, I can't see why the inner function definition is necessary. ...

Alamout":1ro8ligs said:
I don't deal with generators (unlike lostnihilist) because generators aren't sequences, which means I can save some type-checking there.
Fair enough, given the wording of my post, but what makes the problem difficult to generalize is the difference in indexing between different types of iterators, sequences or no. ...
 

herko

Tone down Your Control issues.
7,014
Moderator
I think that what might be a more Pythonic approach to this problem is duck-typing; basically, if it behaves like a string treat it like a string, if it behaves like a dictionary treat it as such. This code relies on two tricks:

  • 1. attack the items in a specific order: stringlikes firsts, then dictionarielikes, then listlikes. The reason is that strings and dicts will be processed (incorrectly) by the list-handling code if it touches them.
    2. both tuples and lists can be concatenated so they can actually be handled the same way
Code:
from copy import copy

test={'key1': ['string with, a comma', ['another string with, a comma']], \
'key2': ('this one, is in a tuple', {'key3': ['that also, has a dictionary in it']},\
'you get, the point'), 'key4': 'I, hope'}


def kill_commas(full_of_commas):
    new_item=copy(full_of_commas)
    try:
        new_item=new_item.replace(',', '')
        return new_item
    except AttributeError:
        pass
    try:
        for k, v in new_item.iteritems():
            new_item[k]=kill_commas(v)
        return new_item
    except TypeError:
        pass # Wasn't a dictionarylike item
    except AttributeError:
        pass # Wasn't a dictionarylike item
    t=type(new_item)
    n=t()
    for k in new_item:
        n+=t((kill_commas(k),))
    return n
    
print kill_commas(test)
 

Alamout

Ars Legatus Legionis
27,285
^ From what I've read, the 'try' portion of try-expect is fast but dealing with exceptions is not. So, using try-except as a way of typing is only a good idea when the majority of your cases are going to work without tripping an exception. I recall reading Guido saying something along these lines, but here is a test with similar results--try is fast (faster than actually checking first), but except is much slower.

Given that, I'm not sure your code would work so great--it could be doing a whole lot of exception handling, depending on the structure of the input.

gloucester":2khar014 said:
I need to go learn how to use generators. Looking at that, I can't see why the inner function definition is necessary. ...
Well...it isn't necessary, I suppose:

Code:
def kill_commas(seq):
    if isinstance(seq, str):
        return seq.replace(',', '')
    else:
        return type(seq)(kill_commas(i) for i in seq)
(well, this version still uses a generator in the last line, but there are no yield statements)
 

herko

Tone down Your Control issues.
7,014
Moderator
Alamout":21oig9gd said:
^ From what I've read, the 'try' portion of try-expect is fast but dealing with exceptions is not. So, using try-except as a way of typing is only a good idea when the majority of your cases are going to work without tripping an exception. I recall reading Guido saying something along these lines, but here is a test with similar results--try is fast (faster than actually checking first), but except is much slower.

You're correct in that exception handling is slow, but I was trying to write a general handler (as requested in the OP), not a fast one. Avoiding the type checks seems pythonic to me.

I guess you could check for existence of the methods you want to use, instead of raising relying on exceptions.

EDIT: fixed the last sentence
 
Status
Not open for further replies.