PHP:
In PHP, we can create a new associative array or dictionary by using the array_combine() function. Just feed two arrays as the parameters to this function and you get back a dictionary. The first array elements are converted into keys and the second array elements are used as values.
1 2 3 4 5 6 7 8 9 |
<?php $a = array('a','b','c'); $b = array('d','e','f'); $arr = array_combine($a,$b); echo $arr['a']; // 'd' echo $arr['b']; // 'e' echo $arr['c']; // 'f' ?> |
Python:
For Python, we first have to zip() two lists into another lists of tuples containing one element from both lists. Then we use the dict() call on this newly created list to create a dictionary.
1 2 3 4 5 6 7 8 |
a = ['a','b','c'] b = ['d','e','f'] l = zip(a,b) d = dict(l) print d['a'] # 'd' print d['b'] # 'e' print d['c'] # 'f' |
I elaborated the process in the above example for beginners. But you’d often see advanced python programmers do it like this:
1 |
d = dict(zip(a,b)) # do it in a single step |