[Python] Moving elements of a python dictionary to another one under certain condition using...

Discussão em 'Python' iniciado por Stack, Abril 5, 2025.

  1. Stack

    Stack Membro Participativo

    OK, so this is more a code "optimization" exercise.

    I have to move all elements from a python dictionary to another, under certain condition, while emptying the source dict at the same time. (No matter I find matching elements or not, the source dict must be empty by the end)

    Let's have:

    pie={"A1":{2000,2001,2002},"A2":{2003,2004,2005},"A3":{2000,2004,2007}} ; slices={}
    condition_check=2000


    As I said, I needed to move the elements to the destination dict only when they meet a certain condition. Match is made on keys and/or values while emptying the source dict, and thus I started with this code (in this case the condition is on values):

    while bool(pie):
    temp = pie.popitem()
    if (condition_check in temp[1]): slices.update({temp[0]:temp[1]})


    Now the question is: is there a way to do without the temp = pie.popitem() line? (I thought perhaps it would be possible using an assignment expression to put it within the if condition maybe?)

    P.S. I know I could go with

    for s in [{k:v} for k,v in pie.items() if (condition_check in v)]: slices.update(s)
    pie.clear()


    or, alternatively

    s = {k:v for k,v in pie.items() if (condition_check in v)} ; slices.update(s)
    pie.clear()


    Finally, I think slices.update({k:v for k,v in pie.items() if (condition_check in v)}) ; pie.clear() could suit well

    Yet I still think things might be better optimizing the first code in such a way that move the temp = pie.popitem() assignment inside the if condition somehow... And I'm just curious to know if is it possible to achieve something like that anyway tbh

    Continue reading...

Compartilhe esta Página