Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Conversion from dictionary to array

Tags:

python

arrays

I have a Python dictionary (say D) where every key corresponds to some predefined list. I want to create an array with two columns where the first column corresponds to the keys of the dictionary D and the second column corresponds to the sum of the elements in the corresponding lists. As an example, if,

D = {1: [5,55], 2: [25,512], 3: [2, 18]}

Then, the array that I wish to create should be,

A = array( [[1,60], [2,537], [3, 20]] )

I have given a small example here, but I would like to know of a way where the implementation is the fastest. Presently, I am using the following method:

A_List = map( lambda x: [x,sum(D[x])] , D.keys() )

I realize that the output from my method is in the form of a list. I can convert it into an array in another step, but I don't know if that will be a fast method (I presume that the use of arrays will be faster than the use of lists). I will really appreciate an answer where I can know what's the fastest way of achieving this aim.

like image 737
Commoner Avatar asked Oct 31 '25 17:10

Commoner


2 Answers

You can use a list comprehension to create the desired output:

>>> [(k, sum(v)) for k, v in D.items()]   # Py2 use D.iteritems()
[(1, 60), (2, 537), (3, 20)]

On my computer, this runs about 50% quicker than the map(lambda:.., D) version.
Note: On py3 map just returns a generator so you need to list(map(...)) to get the real time it takes.

like image 115
AChampion Avatar answered Nov 03 '25 05:11

AChampion


You can try this also:

a=[]
for i in D.keys():
  a+=[[i,sum(D[i])]]
like image 22
Ankur Jyoti Phukan Avatar answered Nov 03 '25 06:11

Ankur Jyoti Phukan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!