1

I am trying to execute this code using for loop,

for i in fielding: # fielding has nearly 19000 records - dtype (list of dictionary)
   for j in player: # player has nearly 17000 records - dtype (list of dictionary)
       if i['id'] == j['id']:
          j['name'] = 'Luke'

So it takes longer time to run. Is there any alternative way to achieve this ? Thanks for your help.

14
  • what data types are fielding, player are they list, tuple, or what? Commented Apr 27, 2021 at 8:29
  • List of dictionary Commented Apr 27, 2021 at 8:30
  • And what is supposed to happen with the outputs? Are you appending? Adding to something else? Or are you just wanting to update your dictionary? Commented Apr 27, 2021 at 8:31
  • No i am trying to update he dictionary. Commented Apr 27, 2021 at 8:33
  • But 'fielding' isn't a list of dictionaries, its just a dictionary correct? Commented Apr 27, 2021 at 8:34

1 Answer 1

6

Looks like you're trying to join data by an identifier (or any other fields). And that's the case when you may use dict or set to speedup id-lookups:

# Build a set of ids you need to update
fielding_ids = {f['id'] for f in fielding}

# Or use dict if you will need to access the records
# fielding_ids = {f['id']: f for f in fielding}

# Update records with corresponding ids from the second list
for p in player:
    if p['id'] in fielding_ids:
        p['name'] = 'Luke'

Python set() and dict() are hashmap-based containers, which are optimized for almost instant key presence checks.

Sign up to request clarification or add additional context in comments.

3 Comments

@saifislam, feel free to do a test with both solutions and compare the execution time.
I think it's pretty close to amortized O(m+n), and there's no way to do it faster. Am I missing something?
I meant @saifs original loop compared to your solution (using 19000*17000)..

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.