2
\$\begingroup\$

I'm using the following code to initialise 8 I/O-ports (i.e. GPIO pins on a Raspberry Pi). That's 4 x 2 pins, each duo controls a switch, A to D, and each duo consists of a pin for On and a pin for Off.

def init_switches():
    switch = {
        'A': dict(On = 22, Off = 12),
        'B': dict(On = 19, Off = 11),
        'C': dict(On = 18, Off = 16),
        'D': dict(On = 15, Off = 13)
        }

    # define all individual pins as output
    for ID in switch:
        for pin in switch[ID]:
            GPIO.setup(switch[ID][pin], GPIO.OUT)

    return switch

I chose this way, a set of dicts, because it allows me to say:

switch = init_switches()
switch['A']['On'] 

The last line makes for nice readable code. However the nested for loop is not so elegant. Isn't there a more concise way?

Edit: I'm deliberately iterating over keys to get to values. Values are pin numbers. Pin numbering is not arbitrary, but has to do with hardware design. It came out this way because it allowed the easiest circuitry to the switch controller. I'm deliberately hiding all that from the coding, because it's a different chapter altogether.

\$\endgroup\$
2
\$\begingroup\$

In both nested loops, it seems you really need the values of dictionaries. You iterate over the keys just to use them to get the values:

for ID in switch:
    for pin in switch[ID]:
        GPIO.setup(switch[ID][pin], GPIO.OUT)

A more direct approach would be to iterate over the values instead of the keys:

for pins in switch.values():
    for pin in pins.values():
        GPIO.setup(pin, GPIO.OUT)

A minor thing, the definition of switch doesn't follow PEP8, because of the spaces around the = when setting the dictionary keywords. This is the recommended style:

switch = {
    'A': dict(On=22, Off=12),
    'B': dict(On=19, Off=11),
    'C': dict(On=18, Off=16),
    'D': dict(On=15, Off=13)
}
\$\endgroup\$
  • 1
    \$\begingroup\$ I see your points. Thanks for making me think about why one way would be more appropriate than another. \$\endgroup\$ – RolfBly Oct 3 '14 at 19:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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