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?
For posterity, it seems like this should be added as a formal answer. (Taken from the comments.)
dict(zip(keys, vals))
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With