adhamncheese adhamncheese - 6 months ago 10
Python Question

How can I implement a dictionary rather than a list in this program?

I have this program that I have written and I used a list because it you can append to it with ease. With a dictionary, you cannot append to it. So I am wondering if there is a way to write this program with a dictionary rather than a list, and if so, how so?

The outcome, I want this to stay the same. It's just when you change

store = []
to a dictionary as
store = {}
, then how do I change the rest of the program where I am changing only specific variables to go from list to dictionary?

def SSN():

store = []

for i in range(0, 100):
store.append([])
i = 0
name = 'key'
while(name != ''):
name = input('Enter Name: ')
if(name == ''):
if(i<1):
break
j=0
while(j < i):
print(store[j][0] + ' has SSN ' + store[j][1])
j = j+1
break
j=0
val = 0
while(j < i):
if(name == store[j][0]):
val = 1
break
j = j + 1
if(val == 1):
update = input(name + ' has SSN ' + store[j][1] + '. Update? ')
if(update == 'y'):
store[j][1] = input('Enter SSN: ')
else:
ssn = input('Enter SSN: ')
store[i].append(name)
store[i].append(ssn)
i = i+1
SSN()


This runs exactly how I want it but it's just that dictionary I would like.
Thanks!

For an outcome, I have this:

Enter Name:
john

Enter SSN:
1234

Enter Name:
mike

Enter SSN:
5678

Enter Name:
wazowski

Enter SSN:
0000

Enter Name:
mike

mike has SSN 5678. Update?
y

Enter SSN:
6644

Enter Name:
john

john has SSN 1234. Update?
n

Enter Name:
john has SSN 1234
mike has SSN 6644
wazowski has SSN 0000


Where the spaced out words represent what the user input when prompted by the program.

Answer

Making store to a dict is a good idea, it would get rid of all the loops you use to find items from it. The changed program would look something like this:

def SSN():
    store = {}
    while True:
        name = input('Enter Name: ')
        if not name:
            for k, v in store.items():
                print(k + ' has SSN ' + v)
            break

        if name in store:
            if input(name + ' has SSN ' + store[name] + '. Update? ') != 'y':
                continue

        store[name] = input('Enter SSN: ')

In the above store.items() returns key value pairs from the dict where key is name and value is SSN. name in store returns boolean value telling if name is in store and store[name] = input('Enter SSN: ') assigns new value replacing the old one if it existed.