Home > Mobile >  Fastest way to iterate over dict of dicts and change only 1 element of the encapsulated dicts
Fastest way to iterate over dict of dicts and change only 1 element of the encapsulated dicts

Time:03-05

Say you have a dict my_dict where all its elements are dictionaries.

What is the fastest way to iterate over all elements and change only 1 element of the encapsulated dict ?

basically this but faster:

for sub_dict in my_dict:
    sub_dict["key_2"] = sub_dict["key_2"][0]

Note: I would be interested if anyone points out a way to do this with lambda functions

CodePudding user response:

So, I rewrote your example (as it not kinda working) and compared with my dict comprehension

import datetime

my_dict = {i: [i ** 2] for i in range(1000000)}

now = datetime.datetime.now()
for sub_dict in my_dict:
    my_dict[sub_dict] = my_dict[sub_dict][0]

print("First", datetime.datetime.now() - now)  # First 0:00:00.088934
my_dict = {i: [i ** 2] for i in range(100000)}

now = datetime.datetime.now()
my_dict = {k: v[0] for k, v in my_dict.items()}  # Second 0:00:00.007972
print("Second", datetime.datetime.now() - now)

CodePudding user response:

This works, should be faster than the for loop. Not sure if it's optimal

[dict(sub_dict,key_2=sub_dict["key_2"][0])(sub_dict) for sub_dict in my_dict]
  • Related