4

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?

1
  • 4
    Simply dict(zip(keys, vals)) Commented May 21, 2017 at 10:24

2 Answers 2

7

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

dict(zip(keys, vals))
Sign up to request clarification or add additional context in comments.

Comments

3

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.