Search code examples
pythonpython-2.7dictionarypython-2.xpython-2.6

How to convert Python dictionary syntax from 2.7 to 2.6?


I am trying to run my script from Jenkins which has Python 2.6 installed. My script was originally written on a Linux machine which uses 2.7.5. Whenever I run the script form my local machine it works fine, but when I try to run it from Jenkins, it throws a syntax error for the following code:

rpmDict = {rpmList[i]: rpmList_full[i] for i in range (len(rpmList))}

rpmDataDict = {rpmDataTextList[i]: rpmDataTextList_full[i] for i in range (len(rpmDataTextList))}

Can someone help me translate this to 2.6 syntax?


Solution

  • So, in both versions this is totally over-engineered.

    rpmDict = {rpmList[i]: rpmList_full[i] for i in range (len(rpmList))}
    

    Should just be:

    rpmDict = dict(zip(rpmList, rpmList_full))
    

    And:

    rpmDataDict = {rpmDataTextList[i]: rpmDataTextList_full[i] for i in range (len(rpmDataTextList))}
    

    Should just be:

    rpmDataDict = dict(zip(rpmDataTextList, rpmDataTextList_full))
    

    But as the other answer has noted, in Python2.6,

    {expression0: expression1 for whatever in some_iterable}
    

    Can be converted into

    dict((expression0, expression1) for whatever in some_iterable)
    

    Note also, you really should be using Python 3 as much as possible. In any case, in Python 2, use:

    from future_builtins import zip
    

    So that zip creates an iterator, not a list, which is more efficient, especially for larger data.