Search code examples
pythondictionarykey

How to let the multiply keys all exist in dictionary? (python)


I have a problem.

I wanna add the same record but the old one will be replaced by a new one! I want both of them exist so I can see what I've done.

How do I solve the problem? Please help me!

Thank you!

my code:

initial_money = int(input('How much money do you have? '))
mr={}
add_mr={}
def records():
    return

def add(records):
    records = input('Add an expense or income record with description and amount:\n').split()
    
    global mr
    global rec
    rec = records[0]
    global amt
    amt = records[1]
    
    for r, a in mr.items():
        i = 0
        while (r, i) in add_mr:
            i += 1
        add_mr[(r, i)] = a
    
    global initial_money
    mr[rec] = int(amt)
    initial_money += mr[rec]
    
def view(initial_money, records):
    print("Here's your expense and income records:") 
    print("Description          Amount")
    print("-------------------  ------")
    for r,a in mr.items():
        print('{name:<20s} {number:<6s}'.format(name = r,number = str(a)))
    print('Now you have {} dollars.'.format(initial_money))   
    
while True:
    command = input('\nWhat do you want to do (add / view / delete / exit)? ')
    if command == 'add':
        records = add(records)
    elif command == 'view':
        view(initial_money, records)

The output:

How much money do you have? 1000

What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
ewq 87

What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
ewq 87

What do you want to do (add / view / delete / exit)? view
Here's your expense and income records:
Description          Amount
-------------------  ------
tree                  87    
Now you have 1174 dollars.

Output I want:

-------------------  ------
tree                  87
tree                  87    

Solution

  • Instead of using a dictonary such that Mr = {"ewq": 87} you could instead use a list of all of them such that Mr = [("ewq", 87), ("ewq", 87)]

    This would make it so that if you have a duplicate it won't overwrite. As dictionaries can only have one per key

    Edit: You would do this by replacing the first part that says mr = {} with mr = [] and then whenever you call addmr you can instead just use mr.append(value) which will add the value to the list