Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash from two arrays/lists in python

Using two Arrays of equal length, how can I create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values).

For example in Java I can use HashMap:

String[] keys= {"apple", "banana", "cherry"};
int[] vals= {1, 2, 3};
HashMap<String, Integer> hash= new HashMap<String, Integer>();

for(int i= 0; i < keys.length; i++){
   hash.put(keys[i], vals[i]);
}

How could do this Python?

like image 937
TheLegend27 Avatar asked Oct 21 '25 10:10

TheLegend27


2 Answers

For posterity, it seems like this should be added as a formal answer. (Taken from the comments.)

dict(zip(keys, vals))
like image 172
Jared Goguen Avatar answered Oct 23 '25 00:10

Jared Goguen


You can use zip inside a dictionary comprehension to achieve the same result in python:

>>> keys = ['apple', 'banana', 'cherry']
>>> values = [1, 2, 3]
>>> hash = {key: value for key, value in zip(keys, values)}
>>> hash
{'apple': 1, 'banana': 2, 'cherry': 3}
like image 20
Sash Sinha Avatar answered Oct 23 '25 01:10

Sash Sinha



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!