2

I am working with a large object a in Python. The object has two other iterable objects b and c passed to it as attributes one and two.

I want to consolidate the important data in the object prior to passing it to the templating engine. I am trying to take an attribute from one and assign it to two.

My first thought was to parse the two objects with two stacked for loops like this..

for c in a.two:
    for a in a.one:
        if a.id == c.id:
            setattr(c, 'title', a.title)

However, I am not sure if this is the most pythonic way of doing this.

2
  • It could be converted to a list comprehension which would probably be a little bit faster. I'm not sure how else it could be improved, but I imagine somebody on here would know how to implement itertools or something to reduce the time complexity of it! Commented Apr 16, 2019 at 20:02
  • Be careful comparing ids as they will sometimes act in unexpected manners especially on multi threaded programs... Commented Apr 16, 2019 at 20:03

1 Answer 1

5

You can improve your code from a time complexity of O(n x m) to O(n + m) (quadratic to linear) by building a dict for each list that maps the ids of objects in the list to the objects, and using set intersection between the dict keys to find the common ids between the two lists instead. Also, you don't need to use the setattr function if the attribute name you're setting is fixed; you can assign to the object's attribute directly instead:

one = {obj.id: obj for obj in a.one}
two = {obj.id: obj for obj in a.two}
for id in set(one).intersection(two):
    two[id].title = one[id].title
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.