The logic of the code to build was as follows, two logical conditions; If the value of dictionary element matches in the list of dictionaries return the particular dictionary, and if no element matches in the list of dictionaries; append this new dictionary element. I have written in the below form for example.

say_element = {'origin': 10}
say_list_two = [{'origin': 8}, {'origin': 9}]

if not any(each['origin'] == say_element['origin'] for each in say_list_two):
    print('not matched') #logic is to append this new dictionary element to the list of dicts

for each in say_list_two:
    if each['origin'] == say_element['origin']:
        #return each['origin'] #for example
        print('Matched') #logic is to return that particular dictionary element from the list

Could I improve the code in a single for loop statement? Is it O(N^2) + O(N^2) as it is going through two for statements? One in the boolean 'if not any.. for items in list' line of code and another. Could I use itertools/generator method to iterate over list of dictionaries one by one, reduces space complexity alone? Any suggestions please?

Edit 1: I have commented out the return statement as it misdirects.

  • 4
    \$\begingroup\$ SyntaxError: 'return' outside function. Please provide a working code. \$\endgroup\$ – stefan Oct 24 '18 at 7:26
  • 1
    \$\begingroup\$ Lacks concrete context: Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site. Please take a look at the help center. \$\endgroup\$ – Mast Oct 24 '18 at 8:29
  • \$\begingroup\$ Okay. Thanks. I would have looked at the help center and edited the post, but why down vote!? Sad. I'll get onto editing the original post nonetheless. \$\endgroup\$ – Rajesh Mappu Oct 24 '18 at 16:50

You can use the for else in python to done it in one for loop

for each in say_list_two:
    if each['origin'] == say_element['origin']:
    print('not matched')

so if no element matches in the list of say_list_two the loop will go else part

I tried generator but the time spend has few difference, using generator to gather all items and use set to find the target item

x = (each['origin'] for each in say_list_two)
if say_element['origin'] in x:
    print('Not Matched')

Full of my test code

from timeit import timeit
from random import randint
a = [{"key":randint(1,100000)} for _ in range(100000)]
b = {"key":66}

def fun1():
    for k in a:
        if k["key"] == b["key"]:
            # print("Matched")
        # print("Not Matched")

def fun2():
    x = (k['key'] for k in a)
    if b['key'] in x:
        # print('Matched')
        # print('Not Matched')r

t1 = timeit("fun1()",'from __main__ import fun1', number=1000)
t2 = timeit("fun2()",'from __main__ import fun2', number=1000)

Time cost

this is linear loop so, time cost is O(N), so does your code. and as my generator implement still using linear loop to gather all values of dictionary in list, so it also cost O(N).

using for else might spend a little less due to it break once find the target item

| improve this answer | |
  • \$\begingroup\$ Thank you for the amazing insight. Learned a lot from your answers Aries. Much appreciated. \$\endgroup\$ – Rajesh Mappu Oct 24 '18 at 16:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.