gwydion93
gwydion93

Reputation: 1923

Dictionary comprehension method not working in Python 2.65

I wrote a script in a Python 3.6 environment and now need to translate it back to Python 2.65. There is one line of code that it particularly disapproves of. I used dictionary comprehension to make a variable. Note: NFHL_sx_firmpan and Prelim_sx_firmpan are dictionaries that I am comparing to find the differences that are 'not shared' between them.-

 unshared = {k: NFHL_sx_firmpan[k] for k in NFHL_sx_firmpan if k not in Prelim_sx_firmpan}

It throws a synatax error on the 'for', so I tried to use an old for loop with a conditional:

 unshared = dict()
 for k in NFHL_sx_firmpan:
     if k not in Prelim_sx_firmpan:
        unshared = k: NFHL_sx_firmpan[k]

It now throws a syntax error on the ':' after 'k'. How can I translate this so that it works in 2.65? (Note2: it works fine asis in 3.6)

Upvotes: 0

Views: 25

Answers (2)

LeKhan9
LeKhan9

Reputation: 1350

The code below should be compatible with version less than Python 2.7

unshared = dict((k, NFHL_sx_firmpan[k]) for k in NFHL_sx_firmpan if k not in Prelim_sx_firmpan)

Upvotes: 1

aedificatori
aedificatori

Reputation: 129

Is there anything preventing you from doing the following? This syntax should work in both versions.

unshared = {}
for k in NFHL_sx_firmpan:
    if k not in Prelim_sx_firmpan:
        unshared[k] = NFHL_sx_firmpan[k]

Upvotes: 1

Related Questions