Collapse dictionary on key
<p>I am having issues reading a CSV into a dictionary and collapsing that dictionary by a key. I have enough code to get to this point (I have all the counties for each state):</p>

<pre><code>{'County': '02013', 'State': 'Alaska', 'Rate': '28.38692673', 'Zip': '99553'}
{'County': '02013', 'State': 'Alaska', 'Rate': '28.38692673', 'Zip': '99571'}
{'County': '02013', 'State': 'Alaska', 'Rate': '28.38692673', 'Zip': '99583'}
{'County': '02013', 'State': 'Alaska', 'Rate': '28.38692673', 'Zip': '99612'}
</code></pre>

<p>But I would like the following result:</p>

<pre><code>{'County': '02013', 'State': 'Alaska', 'Rate': '28.38692673', 'Zips': ['99553', '99571', '99583', '99612']}
</code></pre>

<p>My current python code is:</p>

<pre><code>with open('../models/mock_data/geography_data.csv', 'r') as f:

result = {}
red = csv.DictReader(f)
</code></pre>

<p>I've attempted to add the following:</p>

<pre><code>for d in red:
    result.setdefault(d["County"], [d["State"], d["Rate"]]).append(d["Zip"])
</code></pre>

<p>But that results in data like the following (missing keys)</p>

<pre><code>16079': ['Idaho', '21.02970297', '83802', '83808', '83812', '83837', '83839', '83846', '83849', '83850', '83867', '83868', '83873', '83874']
</code></pre>

<p>There are plenty of other questions similar to this one using <code>iteritems()</code> and <code>setdefaultdict()</code> (like this one: <a href="https://stackoverflow.com/questions/10386566/how-should-i-collapse-elements-in-python">How should I collapse elements in Python?</a>) but I suppose I'm not understanding those processes enough to implement them in my particular case. Any and all help is welcome.</p>

<p>--update--</p>

<p>Ok so @timegb helped me quite a bit but I was most comfortable using a brute force approach:</p>

<pre><code>with open('../models/mock_data/all_geo_data.csv', 'r') as f:
    reader = csv.reader(f)
    header = next(reader)
    dicts = [dict(zip(header, map(str,row))) for row in reader]

    counties = []
    result = []

    for i in dicts:
        zips = []
        if i["County"] not in counties:
            counties.append(i["County"])
            zips.append(i["Zip"])
            temp_dict = {"County": i["County"], "State" : i["State"], "Zip" : zips, "Rate" : i["Median_CNC_Labor_Rate"] }
            result.append(temp_dict)

    for i in dicts:
        for j in result:
            if i["County"] == j["County"] and i["Zip"] not in j["Zip"]:
            j["Zip"].append(i["Zip"])
</code></pre>