Flipped dictionary not working correctly python

import csv



def partytoyear():     #this function associate the party; to the year it was served#
    party_in_power = {}
    with open("presidents.txt") as f:
        reader = csv.reader(f)
        for row in reader:
            party = row[1]
            for year in row[2:]:
                party_in_power[year] = party
    new_dict = {}
    for k, v in party_in_power.items():
        new_dict[v] = k
    print(new_dict)  
partytoyear()

Original dictionary output:

'1961': 'Democrat', '1962': 'Democrat', '1963': 'Democrat', '1964': 'Democrat', '1965': 'Democrat', '1966': 'Democrat', '1967': 'Democrat', '1968': 'Democrat', '1969': 'Republican', '1970': 'Republican', '1971': 'Republican', '1972': 'Republican', '1973': 'Republican', '1974': 'Republican', '1975': 'Republican', '1976': 'Republican', '1977': 'Democrat', '1978':

I needed the keys and values flipped, so I added this code block:

new_dict = {}
    for k, v in party_in_power.items():
        new_dict[v] = k
    print(new_dict) 

they flipped, but now I am only getting 2 results from the dictionary instead of the dozens. Heres the output:

{'Democrat': '2012', 'Republican': '2008'}

Any ideas? Is it not iterating through the for loop all the way?

Upvotes: 0

Views: 32

Answers (1)

kaya3
kaya3

Reputation: 51063

Since multiple keys map to the same value in the original dictionary, each key in the inverse dictionary will need to map to multiple values. A sensible way to do that is have a dictionary of lists:

new_dict = { 'Democrat': [], 'Republican': [] }
for k, v in party_in_power.items():
    new_dict[v].append(k)

A slightly neater solution which doesn't hard-code the keys in the inverse dictionary is to use a defaultdict:

from collections import defaultdict

new_dict = defaultdict(list)
for k, v in party_in_power.items():
    new_dict[v].append(k)

Upvotes: 1

Related Questions