Assigning Python List Values

I would like to take a python dictionary from lists, convert the lists to numpy arrays, and restore them to 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 want to convert the lists under keys A and B to numpy arrays, but not leave the rest of the dictionary intact. Result 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 can this be done with a list? Sort of

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

Or indeed the fastest most effective way to achieve this for large dictionaries of long lists. Thanks labjunky

+4
source share
3 answers

With Python 2.7 and above, you can use the understanding:

 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 are under version 2.7 (and therefore do not understand the dictionary), 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()) 
+3
source

To change all items except 'C' and 'D' :

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

the above dict-comprehension returns a new dictionary to change the original dict, try:

 #myDict.viewkeys() - ignore --> set(['A', 'B']) for key in myDict.viewkeys() - ignore: myDict[key] = np.array(myDict[key]) 

or if you want to change only 'A' and 'B' :

 for key in {'A', 'B'}: myDict[key] = np.array(myDict[key]) 
+1
source

To

take the python dictionary from lists, convert the lists to numpy arrays and restore them in the dictionary using list comprehension.

I would do:

 myDict = {'A':[1,2,3,4], 'B':[5,6,7,8], 'C':'str', 'D':'str'} def modifier(item): if type(item) == list: return np.array(item) else: return item mod_myDict = {key: modifier(myDict[key]) for key in myDict.keys()} 

Then the function sets the required restrictions, in this case changing all the lists into arrays. This returns:

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

Note. I believe that this should be abbreviated using the conditions in the if , but I cannot imagine what it looks like

 mod_myDict = {key: np.array(myDict[key]) if type(myDict[key])==list else key: myDict[key] for key in myDict.keys()} 

This, however, causes an error. Perhaps a smarter person than I know why!

0
source

Source: https://habr.com/ru/post/1499306/


All Articles