6

Could someone help me with the syntax of the following or tell me if it is possible or not? As I am going to modify the if ... else ... condition. I don't want to add duplicated values in the list, but I got a KeyError.

Actually, I am not familiar with this kind of statements:

twins[value] = twins[value] + [box] if value in twins else [box]

what does this exactly mean?

Sample code

#dictionary
twins = dict()                  
#iterate unitlist
for unit in unitlist:                                              
    #finding each twin in the unit
    for box in unit:                            
        value = values[box]                               
        if len(value) == 2: 
            twins[value] = twins[value] + [box] if value in twins else [box]

I modified the condition

#dictionary
twins = dict()                  
#iterate unitlist
for unit in unitlist:                                              
    #finding each twin in the unit
    for box in unit:                            
        value = values[box]                               
        if len(value) == 2:                            
            if value not in twins:                    
                twins[value] = twins[value] + [box]

2 Answers 2

8

This

twins[value] = twins[value] + [box] if value in twins else [box]

is functionally equivalent to this:

if value in twins:
    tmp = twins[value] + [box]
else:
    tmp = [box]
twins[value] = tmp
Sign up to request clarification or add additional context in comments.

1 Comment

Actually "twins[value] = tmp" should be placed inside if-else. Thanks
3

You need to use:

if value in twins:                    
    twins[value] = twins[value] + [box]
else:
    twins[value] = [box]

or if you want to keep your not in condition:

if value not in twins: 
    twins[value] = [box]               
else:    
    twins[value] = twins[value] + [box]

But you could also use dict.get with a default to do it without the if completly:

twins[value] = twins.get(value, []) + [box]

Comments

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.