0

i have a litle question since iam new to python, i came from php and in php iam able to define array with explicit indexes

 array(
         "Index1" => array(),
         "Index2" => array()
         );

Iam wondering if iam able to do the same thing with lists in python, for example

["Index1" => [], "Index2" => []]

2 Answers 2

2

You are talking about dictionary in python. http://docs.python.org/2/library/stdtypes.html#dict

>>> d = {"Index1": [], "Index2": []}
>>> d["Index1"]
[]

or

>>> d = dict(Index1=[], Index2=[])
Sign up to request clarification or add additional context in comments.

2 Comments

I think collections.OrderedDict would be more appropriate.
You may be right. The difference is that collections.OrderedDict is ordered, wheres dictionary is not.
0

The equivalent would be an ordered dictionary:

from collections import OrderedDict

d = OrderedDict([
    ('Index1', []),
    ('Index2', [])
])

Although order is rarely used, so a regular dictionary should be just fine in most cases:

d = {
    'Index1': [],
    'Index2': []
}

Comments

Your Answer

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