Math operations on multi-dimensional Python dicts
<p>I am porting over some code from PHP that iterates through some database results and builds a two-dimensional array of wins and losses for teams in a baseball league. Here's the code in question in PHP</p>

<pre><code>    foreach ($results as $result) {
        $home_team = $result['Game']['home_team_id'];
        $away_team = $result['Game']['away_team_id'];

        if (!isset($wins[$home_team][$away_team])) $wins[$home_team][$away_team] = 0;
        if (!isset($wins[$away_team][$home_team])) $wins[$away_team][$home_team] = 0;
        if (!isset($losses[$home_team][$away_team])) $losses[$home_team][$away_team] = 0;
        if (!isset($losses[$away_team][$home_team])) $losses[$away_team][$home_team] = 0;

        if ($result['Game']['home_score'] &gt; $result['Game']['away_score']) {
            $wins[$home_team][$away_team]++;
            $losses[$away_team][$home_team]++;
        } else {
            $wins[$away_team][$home_team]++;
            $losses[$home_team][$away_team]++;
        }
    }
</code></pre>

<p><code>$results</code> is an array that contains the results of a database query</p>

<p>(Edited to add the Python code I have in-profess)</p>

<p>Now I have this but in Python. <code>results</code> contains a collection of Sqlalchemy result objects</p>

<pre><code>from sqlalchemy import Column, create_engine, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker


Base = declarative_base()
engine = create_engine('postgresql://stats:st@ts=Fun@localhost/ibl_stats')
Session = sessionmaker()
Session.configure(bind=engine)
session = Session()


class Game(Base):
    __tablename__ = 'games'

    id = Column(Integer, primary_key=True)
    week = Column(Integer)
    home_score = Column(Integer)
    away_score = Column(Integer)
    home_team_id = Column(Integer, ForeignKey('franchises.id'))
    away_team_id = Column(Integer, ForeignKey('franchises.id'))


class Franchise(Base):
    __tablename__ = 'franchises'

    id = Column(Integer, primary_key=True)
    nickname = Column(String(3))
    name = Column(String(50))
    conference = Column(String(10))
    division = Column(String(10))
    ip = Column(Integer)

# Loop through our standings building up the breakdown results
results = session.query(Game).all()
wins = dict()
losses = dict()

for result in results:
    home_team = result.home_team_id
    away_team = result.away_team_id

    if result.home_score &gt; result.away_score:
        wins[home_team][away_team] += 1
        losses[away_team][home_team] += 1
    else:
        wins[away_team][home_team] += 1
        losses[home_team][away_team] += 1
</code></pre>

<p>So when I run this code I get the following error:</p>

<pre><code>(venv)vagrant@ibl:/vagrant/scripts$ python playoff_odds.py
Traceback (most recent call last):
  File "playoff_odds.py", line 45, in &lt;module&gt;
    wins[home_team][away_team] += 1
KeyError: 1
</code></pre>

<p>I did some searching before and it starts getting into the concept of "autovivification", which is something PHP does by default but Python does not.</p>

<p>So how do I duplicate the same behaviour in the Python code?</p>

<p>I think I would probably use namedtuples here, but it's hard to tell from just this snippet.</p>

<p>If you'd like material on how to write more Pythonic code, I recommend checking out Raymond Hettinger's videos, particularly</p>

<p>"Best practices for beautiful intelligible code" and
"Transforming Code into Beautiful, Idiomatic Python":  </p>

<p><a href="http://pyvideo.org/speaker/raymond-hettinger.html" rel="nofollow">http://pyvideo.org/speaker/raymond-hettinger.html</a></p>

python dictionary