Python Dictionary value assignment with list comprehension
Question: I would like to take a python dictionary of lists, convert the lists to numpy
arrays, and restore them in the dictionary using list comprehension.

For example, if I had a dictionary

    
    
    myDict = {'A':[1,2,3,4], 'B':[5,6,7,8], 'C':'str', 'D':'str'}
    

I wish to convert the lists under keys A and B to numpy arrays, but leave the
other parts of the dictionary untouched. Resulting in

    
    
    myDict = {'A':array[1,2,3,4], 'B':array[5,6,7,8], 'C':'str', 'D':'str'}
    

I can do this with a for loop:

    
    
    import numpy as np
    
    for key in myDict:
        if key not in ('C', 'D'):
            myDict[key] = np.array(myDict[key])
    

But is it possible to do this with list comprehension? Something like

    
    
    [myDict[key] = np.array(myDict[key]) for key in myDict if key not in ('C', 'D')]
    

Or indeed what is the fastest most efficient way to achieve this for a large
dictionaries of long lists. Thanks, labjunky


Answer: With Python 2.7 and above, you can use a [dictionary
comprehension](http://docs.python.org/2/tutorial/datastructures.html#dictionaries):

    
    
    myDict = {'A':[1,2,3,4], 'B':[5,6,7,8], 'C':'str', 'D':'str'}
    myDict = {key:np.array(val) if key not in {'C', 'D'} else val for key, val in myDict.iteritems()}
    

If you're below version 2.7 (and hence don't have dictionary comprehensions),
you can do:

    
    
    myDict = {'A':[1,2,3,4], 'B':[5,6,7,8], 'C':'str', 'D':'str'}
    dict((key, np.array(val) if key not in {'C', 'D'} else val for key, val in myDict.iteritems())
    

