-1
\$\begingroup\$

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):
    say_list_two.append(say_element)
    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.

\$\endgroup\$

closed as off-topic by l0b0, Ludisposed, Mast, Toby Speight, Ismael Miguel Oct 24 '18 at 15:55

This question appears to be off-topic. The users who voted to close gave these specific reasons:

  • "Code not implemented or not working as intended: Code Review is a community where programmers peer-review your working code to address issues such as security, maintainability, performance, and scalability. We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review." – l0b0, Ludisposed, Ismael Miguel
  • "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." – Mast, Toby Speight
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 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
0
\$\begingroup\$

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('Matched')
        break
else:
    say_list_two.append(say_element)
    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('Matched')
else:
    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")
            return
    else:
        # print("Not Matched")
        return


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


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

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

\$\endgroup\$
  • \$\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.