Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

This feels like a stupid question, but I cannot find an answer anywhere. I am trying to learn python, so I figured I could try to create a little command line control for my lights and locks etc. (I have made my own home automation with Arduino).

To my question: I want the Python equivalent to PHP's:

$array = array('light' => array('on', 'off'), 'lock' => array('lock', 'unlock'));

Any feedback would be greatly appreciated.

share|improve this question
up vote 1 down vote accepted

In Python you can use a dictionary for this:

>>> dct = {'light': ['on', 'off'], 'lock': ['lock', 'unlock']}
>>> dct
{'lock': ['lock', 'unlock'], 'light': ['on', 'off']}

Another option is to use the dict() constructor, but this requires the keys to be valid Python identifiers:

>>> dct = dict(light=['on', 'off'], lock=['lock', 'unlock'])
>>> dct
{'lock': ['lock', 'unlock'], 'light': ['on', 'off']}

Note that the above two methods won't preserve the order though, if order matters then you should use collections.OrderedDict:

>>> from collections import OrderedDict
>>> dct = OrderedDict((('light', ['on', 'off']), ('lock',['lock', 'unlock'])))
>>> dct
OrderedDict([('light', ['on', 'off']), ('lock', ['lock', 'unlock'])])
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.