Home > Software design >  how to create a new dictionary by processing the original one
how to create a new dictionary by processing the original one

Time:04-26

Here is the instruction: Create a new dict (by processing the original dict) with Term as the key and a list of (amount, rate) tuples for each Term key.

This function returns the dictionary of the Mortgages

def getMortgages():
    m_dict = {'867E23': (208000, 0.015, 120), '837E23': (156000, 0.030, 180), '467E23': (720000, 0.065, 240),
              '337E23': (333000, 0.087, 120), '829E23': (241000, 0.0315, 240), '867W35': (187000, 0.033, 180),
              '86E87': (165000, 0.063, 90), '86A3E3': (132000, 0.0312, 120), '367W51': (500000, 0.055, 360),
              '327Q65': (320000, 0.0321, 180), '837C09': (432000, 0.0516, 240), '863M88': (812000, 0.0628, 360),
              '862W76': (333000, 0.0445, 180), '86NE2B': (446000, 0.0443, 240), '862A42': (778000, 0.0523, 360)}
    return m_dict

Here is how I create the new dictionary:

mortgageAmount = getMortgages()
mortgageNew = dict((term, (amount, rate)) for amount, rate, term in mortgageAmount.values())
    print(mortgageNew)

But now it sums up all the values of amount and rate, {120: (132000, 0.0312), 180: (333000, 0.0445), 240: (446000, 0.0443), 90: (165000, 0.063), 360: (778000, 0.0523)}

I was wondering why and how could I fix that to display each amount and rate instead up summing them up, like this:

120:[(100000,.02), (200000,.03)],
240:[(150000,0.0315)...],
...```

CodePudding user response:

The output you've shown doesn't seem to tally with the input. Having said that, I think this is what you're trying to do:

m_dict = {'867E23': (208000, 0.015, 120), '837E23': (156000, 0.030, 180), '467E23': (720000, 0.065, 240),
          '337E23': (333000, 0.087, 120), '829E23': (241000, 0.0315, 240), '867W35': (187000, 0.033, 180),
          '86E87': (165000, 0.063, 90), '86A3E3': (132000, 0.0312, 120), '367W51': (500000, 0.055, 360),
          '327Q65': (320000, 0.0321, 180), '837C09': (432000, 0.0516, 240), '863M88': (812000, 0.0628, 360),
          '862W76': (333000, 0.0445, 180), '86NE2B': (446000, 0.0443, 240), '862A42': (778000, 0.0523, 360)}

n_dict = dict()

for x, y, z in m_dict.values():
    n_dict.setdefault(z, []).append((x, y))

print(n_dict)

Output:

{120: [(208000, 0.015), (333000, 0.087), (132000, 0.0312)], 180: [(156000, 0.03), (187000, 0.033), (320000, 0.0321), (333000, 0.0445)], 240: [(720000, 0.065), (241000, 0.0315), (432000, 0.0516), (446000, 0.0443)], 90: [(165000, 0.063)], 360: [(500000, 0.055), (812000, 0.0628), (778000, 0.0523)]}
  • Related