Creating Dictonaries from Arrays / Lists

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.

<?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.

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:

d = dict(zip(a,b)) # do it in a single step
This entry was posted in Blog Post and tagged , . Bookmark the permalink.

One Response to Creating Dictonaries from Arrays / Lists

  1. Pingback: Twitted by masnun

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">