cant figure out why im getting an key error in python [closed] - python-3.x

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 14 hours ago.
Improve this question
so, I'm doing this final for school and I can't for the life of me figure out why I'm getting a key Error for 'item' in my code at line 33. any help would be appreciated.
rooms = {
'Cart': {'name': 'Cart', 'East': 'Market District'},
'Market District': {'name': 'Market District', 'South': 'Grayson Armory', 'North': 'Temporal Steel',
'East': 'Mini Mart', 'West': 'Cart', 'item': 'Helm'},
'Temporal Steel': {'name': 'Temporal Steel', 'South': 'Market District',
'East': 'Temporal Storage', 'item': 'Sword'},
'Temporal Storage': {'name': 'Temporal Storage', 'West': 'Temporal Steel', 'item': 'Shield'},
'Grayson Armory': {'name': 'Grayson Armory', 'North': 'Market District', 'East': 'Luds', 'item': 'Chest Plate'},
'Luds': {'name': 'Luds', 'East': 'Grayson Armory', 'item': 'Leggings'},
'Mini Mart': {'name': 'Mini Mart', 'North': 'Gate', 'West': 'Market District', 'item': 'Boots'},
'Gate': {'name': 'Gate', 'South': 'Mini Mart', 'item': 'Gate Guard'}
}
def intructions():
print('Welcome to Carts & Burglars')
print('To escape you must collect all the items and avoid the guards!')
print("The commands to move are 'North', 'South', 'East', and 'West' ")
print("To add an item to inventory: get item ")
intructions()
current_room = rooms['Cart'] # initial room
directions = ['North', 'South', 'East', 'West']
item = ['Helm', 'Chest Plate', 'Leggings', 'Sword', 'Shield', 'Boots']
inventory = {} # players inventory
while True:
print('-' * 35)
print('You are in the {}'.format(current_room['name']))
print('Your inventory: {}\n'.format(inventory))
if current_room['item']:
print('Item in room: {}'.format(''.join(current_room['item'])))
print('')
direction = input('Enter an direction:').title()
if direction in directions:
if direction in current_room:
current_room = rooms[current_room[direction]]
if current_room['name'] == 'Gate':
print("You've reached the gate but the guards coming back!")
if len(inventory.keys()) >= 6:
print('you took out the guard!')
print("You've gotten past the gate and no one knows where you went you have achieved freedom.")
else:
print('The guard noticed you and apprehended you')
print('Game Over.')
break
else:
print('Choose a direction')
elif direction == 'get item':
if current_room['item'] != 'none':
inventory['item' + str(len(inventory.keys()) + 1)] = current_room['item']
print("You looted: ", current_room['item'])
print(inventory)
current_room['item'] = 'none'
else:
print("theres nothing here to loot")
elif direction == 'quit':
print('Maybe next time!')
break
else:
print('Invalid input.')
I've tried manipulating the inventory and item variables at the top of the code as well deleting like 33-35 and it works just fine but I need the items to be there and to state what items are in the room.
type here

Related

Adding 'region' column based on 'state' column value but 'region' values all the same

I have a df 'beersmerged' which contains a column 'state'. I am attempting to create a column 'region' which evaluates the value in 'state' and adds the appropriate value to 'region'.
This code runs without error and creates the 'region' column, but every row has the same value - None. I've tried several other approaches and they all have a similar result in that they put the same value in every row. Thanks in advance for any assistance you can provide!
def get_region(state, *region):
if state in region[0]:
return 'New_England'
elif state in region[1]:
return 'Mid_Atlantic'
elif state in region[2]:
return 'South'
elif state in region[3]:
return 'Midwest'
elif state in region[4]:
return 'Southwest'
elif state in region[5]:
return 'West'
else:
return None
New_England = ['CT', 'ME', 'MA', 'NH', 'RI', 'VT']
Mid_Atlantic = ['DC', 'DE', 'MD', 'NJ', 'NY', 'PA']
South = ['AL', 'AR', 'FL', 'GA', 'KY', 'LA', 'MS', 'MO', 'NC', 'SC', 'TN', 'VA', 'WV']
Mid_West = ['IL', 'IN', 'IA', 'KS', 'MI', 'MN', 'NE', 'ND', 'OH', 'SD', 'WI']
Southwest = ['AZ', 'NM','OK', 'TX']
West = ['AK', 'CA', 'CO', 'HI', 'ID', 'MT', 'NV', 'OR', 'UT', 'WA', 'WY']
region = [New_England, Mid_Atlantic, South, Midwest, Southwest, West]
beersmerged['region'] = beersmerged['state'].apply(get_region, args=(region))
beersmerged.head()
I've also tried this using the lists above and it runs without error but puts a 0 for 'region' in every row:
class_regions ={'New_England':New_England,'Mid_Atlantic':Mid_Atlantic,'South':South,'Midwest':Midwest,'Southwest':Southwest,'West':West}
dict_cond_values = {key:beersmerged['state'].isin(class_regions[key]) for key in class_regions}
beersmerged['region']=np.select(dict_cond_values.values(),dict_cond_values.keys())
beersmerged.head()
I was expecting something like this:
state region
OR West
IN Midwest
TX Southwest
NH New_England
VA Mid_Atlantic
But get this:
state region
OR None
IN None
TX None
NH None
VA None
In the original version, specify with a comma that the type of args is tuple as it's required and get rid of asterisk * in front of region parameter of the get_region.
get_region(state, region):
...
beersmerged['region'] = beersmerged['state'].apply(get_region, args=(region,))
But I think it's better to use dict instead of list.
def get_region(state, region):
if state in region['New_England']:
return 'New_England'
elif state in region['Mid_Atlantic']:
return 'Mid_Atlantic'
elif state in region['South']:
return 'South'
elif state in region['Midwest']:
return 'Midwest'
elif state in region['Southwest']:
return 'Southwest'
elif state in region['West']:
return 'West'
else:
return None
New_England = ['CT', 'ME', 'MA', 'NH', 'RI', 'VT']
Mid_Atlantic = ['DC', 'DE', 'MD', 'NJ', 'NY', 'PA']
South = ['AL', 'AR', 'FL', 'GA', 'KY', 'LA', 'MS', 'MO', 'NC', 'SC', 'TN', 'VA', 'WV']
Mid_West = ['IL', 'IN', 'IA', 'KS', 'MI', 'MN', 'NE', 'ND', 'OH', 'SD', 'WI']
Southwest = ['AZ', 'NM','OK', 'TX']
West = ['AK', 'CA', 'CO', 'HI', 'ID', 'MT', 'NV', 'OR', 'UT', 'WA', 'WY']
region = {'New_England': New_England, 'Mid_Atlantic': Mid_Atlantic, 'South': South, 'Midwest': Midwest, 'Southwest': Southwest, 'West': West}
beersmerged['region'] = beersmerged['state'].apply(get_region, args=(region,))
beersmerged.head()

Parallelise / Threading a big for loop | Python

I have a working Jupyter Notebook that models fake data in the form of a dictionary. Using Faker library and other basic Python.
Reading other posts, parallelism seems to be used on methods. However, I want to apply this technique on the big for loop; as I have many more "key-value lists" applied in the process.
Note: I've appended comments of list slicing included in the process, in case that's needed.
Is it possible to run multiple iterations of a for loop at once? (or as many as possible)
from faker import Faker
faker = Faker()
Faker.seed(1)
import pandas as pd
import random
random.seed(1)
# Key Value lists
biographic_keys = [['Name', 'faker.unique.name()'], ['Aliases', 'faker.unique.user_name()'], ['Date of birth', 'faker.unique.date_of_birth().isoformat()'], ['Phone numbers', 'faker.unique.phone_number()'], ['Addresses', 'faker.unique.address()'], ['Nationality', 'faker.unique.country()'], ['Social Security Number', 'faker.unique.ssn()'], ['Alien File Number', 'random.randrange(1000000, 999999999, random.randint(7, 9))']]
biometric_keys = [['Height', "'{}ft {}inch'.format(random.randint(4, 7), random.randint(0, 11)) if random.randint(0, 1) == 1 else '{}cm'.format(random.randint(100, 200))"], ['Weight', "'{}kg'.format(random.randint(60, 130)) if random.randint(0, 1) == 1 else '{}st {}lb'.format(random.randint(7, 50), random.randint(0, 13))"], ['Eye color', "random.choice(['Amber', 'Blue', 'Brown', 'Gray', 'Green', 'Hazel'])"], ['Hair color', "random.choice(['Brown', 'Blond', 'Black', 'Auburn', 'Red', 'Gray', 'White', 'Bald'])"]]
entries = 4
alien_key_val = []
alien_key_val.append(["Biographic data", biographic_keys])
alien_key_val.append(["Biometric data", biometric_keys])
#print(alien_key_val[0]) # name, subset
#print(alien_key_val[0][0]) # name
#print(alien_key_val[0][1]) # subset
#print(alien_key_val[0][1][0][0]) # key
#print(alien_key_val[0][1][0][1]) # invoke val
# Programmatic key-values
alien_dict = {}
for entry in range(1, entries+1):
entry_dict = {}
for i, subset in enumerate(alien_key_val):
subset_dict = {}
subset_name = alien_key_val[i][0]
for data in subset[1]:
key, invoc = data[0], data[1]
#if ('faker.unique.' in invoc) or ('random.' in invoc) or ('tf.' in invoc) or ("''.join" in invoc) or ("'{}" in invoc): val = eval(invoc)
if invoc[-1] != ':': val = eval(invoc)
else: val = ""
if 'Identification numbers' in key: val = {i[0]: i[1] for i in val}
subset_dict.update({key: val})
entry_dict.update({subset_name: subset_dict})
alien_dict.update({'id_' + str(entry): entry_dict})
print("\nALIEN_DICT:\n", alien_dict)
>>> ALIEN_DICT:
{'id_1': {'Biographic data': {'Name': 'Ryan Gallagher', 'Aliases': 'david77', 'Date of birth': '1994-03-12', 'Phone numbers': '(317)066-9074x3915', 'Addresses': '806 Tanya Stream\nNew Jeffreymouth, OH 31051', 'Nationality': 'Guatemala', 'Social Security Number': '237-87-3585', 'Alien File Number': 119580763}, 'Biometric data': {'Height': '4ft 7inch', 'Weight': '120kg', 'Eye color': 'Hazel', 'Hair color': 'White'}}, 'id_2': {'Biographic data': {'Name': 'Tiffany House', 'Aliases': 'jmonroe', 'Date of birth': '1992-12-05', 'Phone numbers': '241-586-8344', 'Addresses': '690 Sanchez Union Suite 625\nChristopherhaven, WI 21957', 'Nationality': 'Maldives', 'Social Security Number': '861-51-6071', 'Alien File Number': 177366680}, 'Biometric data': {'Height': '4ft 6inch', 'Weight': '60kg', 'Eye color': 'Hazel', 'Hair color': 'Bald'}}, 'id_3': {'Biographic data': {'Name': 'Allen Williams DDS', 'Aliases': 'kholland', 'Date of birth': '1973-11-13', 'Phone numbers': '038.836.8595', 'Addresses': '890 Bowers View Apt. 883\nHerringfort, MN 75211', 'Nationality': 'Mexico', 'Social Security Number': '205-65-6774', 'Alien File Number': 775747704}, 'Biometric data': {'Height': '175cm', 'Weight': '27st 0lb', 'Eye color': 'Amber', 'Hair color': 'Brown'}}, 'id_4': {'Biographic data': {'Name': 'Mr. Gregory Ryan', 'Aliases': 'stephen03', 'Date of birth': '1991-12-27', 'Phone numbers': '(892)184-0110', 'Addresses': '41925 Jones Estate Suite 824\nShawnmouth, NJ 15468', 'Nationality': 'Anguilla', 'Social Security Number': '320-50-5626', 'Alien File Number': 655004368}, 'Biometric data': {'Height': '148cm', 'Weight': '34st 11lb', 'Eye color': 'Amber', 'Hair color': 'Auburn'}}}
Solution appended below. Please add a solution if you believe yours is a better alternative. I'd love to learn other approaches for the future.
Inspired by Simple multithread for loop in Python
top solution.
Using multiprocessing.dummy as mp and converting my for loop grand procedure into a function.
All "entry" dictionaries are collected into list dicts and are added to dictionary big_boi_dict as originally intended.
...
def alien_dict_func(entry):
# Programmatic key-values
alien_dict = {}
entry_dict = {}
for i, subset in enumerate(alien_key_val):
subset_dict = {}
subset_name = alien_key_val[i][0]
for data in subset[1]:
key, invoc = data[0], data[1]
#if ('faker.unique.' in invoc) or ('random.' in invoc) or ('tf.' in invoc) or ("''.join" in invoc) or ("'{}" in invoc): val = eval(invoc)
if invoc[-1] != ':': val = eval(invoc)
else: val = ""
if 'Identification numbers' in key: val = {i[0]: i[1] for i in val}
subset_dict.update({key: val})
entry_dict.update({subset_name: subset_dict})
alien_dict.update({'id_' + str(entry): entry_dict})
#print("\nALIEN_DICT:\n", alien_dict)
return alien_dict
import multiprocessing.dummy as mp
if __name__=="__main__":
p=mp.Pool(4)
dicts = p.map(alien_dict_func, range(1, entries+1)) # range(0,1000) if you want to replicate your example
#print("DICTS: ", dicts)
big_boi_dict = {}
for d in dicts: big_boi_dict.update(d)
print("big_boi_dict: ", big_boi_dict)
p.close()
p.join()
>>> big_boi_dict: {'id_1': {'Biographic data': {'Name': 'Jacob Gaines', 'Aliases': 'laurenswanson', 'Date of birth': '2016-04-20', 'Phone numbers': '630-868-7169x899', 'Addresses': '0340 Lydia Passage Suite 898\nAliciaside, NC 54017', 'Nationality': 'Netherlands Antilles', 'Social Security Number': '646-75-5043', 'Alien File Number': 216185864}, 'Biometric data': {'Height': '4ft 3inch', 'Weight': '84kg', 'Eye color': 'Gray', 'Hair color': 'Blond'}}, 'id_2': {'Biographic data': {'Name': 'Carlos Wallace', 'Aliases': 'andreabray', 'Date of birth': '1927-09-11', 'Phone numbers': '069-056-6401x106', 'Addresses': '7567 Timothy Drive Suite 202\nMichealberg, WY 38137', 'Nationality': 'Zambia', 'Social Security Number': '423-34-8418', 'Alien File Number': 472177351}, 'Biometric data': {'Height': '7ft 0inch', 'Weight': '111kg', 'Eye color': 'Amber', 'Hair color': 'Brown'}}, 'id_3': {'Biographic data': {'Name': 'Jason Hill', 'Aliases': 'kimberly73', 'Date of birth': '2002-11-20', 'Phone numbers': '661.123.2301x4271', 'Addresses': '16908 Amanda Key\nLake Taraville, OH 89507', 'Nationality': 'Italy', 'Social Security Number': '855-86-1944', 'Alien File Number': 20427192}, 'Biometric data': {'Height': '125cm', 'Weight': '77kg', 'Eye color': 'Brown', 'Hair color': 'White'}}, 'id_4': {'Biographic data': {'Name': 'Melinda White PhD', 'Aliases': 'hartmanerica', 'Date of birth': '1917-05-19', 'Phone numbers': '(174)876-1971x2693', 'Addresses': '8478 Kristina Road Suite 710\nSaraview, ND 82480', 'Nationality': 'French Southern Territories', 'Social Security Number': '779-13-3745', 'Alien File Number': 501832948}, 'Biometric data': {'Height': '148cm', 'Weight': '128kg', 'Eye color': 'Gray', 'Hair color': 'Auburn'}}}
For the question of accessing every element in the loop simultaneously. I tried something like that
import time
import threading
class handle_data(threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self): # handle_data
print ("Starting " + self.name)
print(self.name, 5, self.counter)
print("Exiting " + self.name)
def stop(self):
self.running = False
if __name__ == "__main__":
for data in range(10):
handle_data(data,"Thread-"+str(data),data).start()

Need help defining a function for text based game

I am trying to code out a function for this project. I am new to python and am taking a class online for it. I am trying to define a function that will read what room my player is in and to give the riddle associated with it. so far this is what I have, there is another dictionary that current_room works with. I just keep getting key errors when trying to test run. If there is a better way to do this as well, please let me know.
EDIT: updating with whole code
# The dictionary links a room to other rooms.
rooms = {'Warehouse Storage': {'name': 'Warehouse Storage', 'south': 'Stamping Area',
'text': 'You are in the Warehouse Storage.'},
'Machine Shop': {'name': 'Machine Shop', 'east': 'Scrap Pile', 'south': 'Staging Area',
'text': 'You are in the Machine Shop.'},
'Front Offices': {'name': 'Front Offices', 'west': 'Lunchroom',
'text': 'You are in Front Offices.'},
'Stamping Area': {'name': 'Stamping Area', 'west': 'Staging Area', 'north': 'Warehouse Storage',
'text': 'You are in the Stamping Area'},
'Loading Docks': {'name': 'Loading Docks', 'east': 'Staging Area',
'text': 'You are in the Loading Docks'},
'Staging Area': {'name': 'Staging Area', 'east': 'Stamping Area', 'west': 'Loading Docks',
'south': 'Lunchroom', 'north': 'Machine Shop',
'text': 'You are in the Staging Area'},
'Lunchroom': {'name': 'Lunchroom', 'north': 'Staging Area', 'east': 'Front Offices',
'text': 'You are in the Lunchroom'},
'Scrap Pile': {'name': 'Scrap Pile', 'west': 'Machine Shop',
'text': 'You are in the Scrap Pile'}
}
riddles = {'Warehouse Storage': {'name': 'Warehouse Storage', 'question': '', 'answer': ''},
'Machine Shop': {'name': 'Machine Shop', 'question': '', 'answer': ''},
'Stamping Area': {'name': 'Stamping Area', 'question': '', 'answer': ''},
'Staging Area': {'name': 'Staging Area', 'question': '', 'answer': ''},
'Lunchroom': {'name': 'Lunchroom', 'question': 'riddle', 'answer': 'yes'},
'Scrap Pile': {'name': 'Scrap Pile', 'question': '', 'answer': ''}
}
# define function that reads room and prompts user with riddle
def room_puzzle(current_room):
global user_inventory
if current_room in riddles.keys():
riddle = input(f'{riddles[current_room]["question"]} \n').strip()
if riddle == riddles[current_room]['answer']:
user_inventory += 1
print('You gained a key')
else:
print('that is incorrect')
return user_inventory
else:
print("no such room")
# determine command regardless of capitalization
def dir_input(text):
if text.upper().startswith('W'):
return 'west'
elif text.upper().startswith('N'):
return 'north'
elif text.upper().startswith('S'):
return 'south'
elif text.upper().startswith('E'):
return 'east'
elif text.upper().startswith('Q'):
return 'quit'
directions = ['north', 'south', 'east', 'west']
current_room = rooms['Front Offices']
print('Would you like to play a game?')
start = input()
game_start = False
user_inventory = 0 # start at zero
if start == 'yes' or start == 'Yes':
game_start = True
# game loop
while game_start == True:
# win condition
if current_room['name'] == 'Loading Docks':
if user_inventory == 6:
print(current_room['text'])
else:
print('6 keys are required to enter')
# display current location
print()
print(current_room['text'])
# get user input
command = input('\nWhat do you do? ').strip()
# show inventory
if command == 'show inventory':
print('You have {} keys'.format(user_inventory))
# movement
elif command in directions:
command = dir_input(command)
if command in current_room:
current_room = rooms[current_room[command]]
#room_puzzle()
else:
# not a valid input
print("You can't go that way.")
# quit game
elif command == 'quit':
break
# does not compute
else:
print("I don't understand that command.")
See basically what I observe from the above code is that you want to check whether the current_room is equal to Lunchroom or not or for any other rooms you have in your riddles dictionary.
So for that, you have to check for the presence of a key in the dictionary not for the values. Also, the below part is incorrect in your code
if current_room in riddles['name']:
instead, it should be
if current_room in riddles.keys():
and the part of code if riddle == riddles['answer']: is incorrect as the you are not passing the right reference to the dictionary key
it should be if riddle == riddles[current_room]['answer']:
so here is the correct code with the working demo for you to understand.
riddles = {'Lunchroom': {'name': 'Lunchroom', 'question': 'riddle?', 'answer': 'yes'}}
def room_puzzle(current_room):
global user_inventory
if current_room in riddles.keys():
riddle = input('{}'.format(riddles[current_room]['question'])).strip()
if riddle == riddles[current_room]['answer']: # here you have to define the refrence to the dictionary value, using the parent key first
# user_inventory += 1
print('You gained a key')
else:
print('that is incorrect')
# return user_inventory
else:
print("no such room")
current_room = 'Lunchroom' #let's assume for now
room_puzzle(current_room)
current_room = 'Someroom' #let's now change the current_room and check that
room_puzzle(current_room)

Lists to Dictionary

I have lists like this
a = ['CROXE-1478','CROXE-9087','CROXE-8744']
b = ['ENGINEER_NAME','DESCRIPTION']
c = ['John','Mark','Rock']
d = ['M5 Cloud decrease even if answer is OK!','Make auto-answer not working.','M5 6200 raised in case of suiteId modified']
I want to create a dictionary like this
dict1 = {'CROXE-1478':{'ENGINEER_NAME':'John','DESCRIPTION':'M5 Cloud decrease even if answer is OK!'},'CROXE-9087':{'ENGINEER_NAME':'Mark','DESCRIPTION':'Make auto-answer not working.'},'CROXE-8744':{'ENGINEER_NAME':'Rock','DESCRIPTION':'M5 6200 raised in case of suiteId modified'}}
This works:
a=['CROXE-1478','CROXE-9087','CROXE-8744']
b = ['ENGINEER_NAME','DESCRIPTION']
c = ['John','Mark','Rock']
d = ['M5 Cloud decrease even if answer is OK!','Make auto-answer not working.','M5 6200 raised in case of suiteId modified']
mainDict = {a[0]:None,a[1]:None,a[2]:None}
for i in range(0,3):
subDict = {b[0]:c[i],b[1]:d[i]}
mainDict[a[i]] = subDict
print(mainDict)
Code:
dict1 = {code: {b[0]: name, b[1]: text} for code, name, text in zip(a, c, d)}
Output:
{'CROXE-1478': {'ENGINEER_NAME': 'John', 'DESCRIPTION': 'M5 Cloud decrease even if answer is OK!'}, 'CROXE-9087': {'ENGINEER_NAME': 'Mark', 'DESCRIPTION': 'Make auto-answer not working.'}, 'CROXE-8744': {'ENGINEER_NAME': 'Rock', 'DESCRIPTION': 'M5 6200 raised in case of suiteId modified'}}
Use this code if your a,c and d has same length
a = ['CROXE-1478', 'CROXE-9087', 'CROXE-8744']
b = ['ENGINEER_NAME', 'DESCRIPTION']
c = ['John', 'Mark', 'Rock']
d = ['M5 Cloud decrease even if answer is OK!', 'Make auto-answer not working.',
'M5 6200 raised in case of suiteId modified']
main_dict = {}
for i in range(len(a)):
dic1 = {}
dic1[b[0]] = c[i]
dic1[b[1]] = d[i]
main_dict[a[i]] = dic1
print main_dict
Output-
{'CROXE-1478': {'ENGINEER_NAME': 'John', 'DESCRIPTION': 'M5 Cloud decrease even if answer is OK!'}, 'CROXE-8744': {'ENGINEER_NAME': 'Rock', 'DESCRIPTION': 'M5 6200 raised in case of suiteId modified'}, 'CROXE-9087': {'ENGINEER_NAME': 'Mark', 'DESCRIPTION': 'Make auto-answer not working.'}}
models = ['CROXE-1478','CROXE-9087','CROXE-8744']
headings = ['ENGINEER_NAME','DESCRIPTION']
engineers = ['John','Mark','Rock']
notes = ['M5 Cloud decrease even if answer is OK!',
'Make auto-answer not working.',
'M5 6200 raised in case of suiteId modified']
result = {}
for model,engineer,note in zip(models,engineers,notes):
designation,description = headings[:]
result[model] = {designation:engineer, description:note }
print(result)
Result
{'CROXE-1478': {'ENGINEER_NAME': 'John',
'DESCRIPTION': 'M5 Cloud decrease even if answer is OK!'},
'CROXE-9087': {'ENGINEER_NAME': 'Mark',
'DESCRIPTION': 'Make auto-answer not working.'},
'CROXE-8744': {'ENGINEER_NAME': 'Rock',
'DESCRIPTION': 'M5 6200 raised in case of suiteId modified'}
}
Note On zip function
zip will take first element from the two list and return a tuple,
after that it goes for the second elements from both f the lists
names = ['linus','richard']
ages = [47,60]
for item in zip(names,ages):
print(item)

Comparing With Dictionary Values(?)

I'm currently working on a self project, a simple ATM. I'm using a dictionary which has a set name, pin, and amount of money for savings and checking accounts. When I try to compare values from a dictionary and a user input, for some reason it doesn't work.
bank = [
{'UserName': 'Bob', 'PIN': '0001', 'CheckingBalance': '1234', 'SavingsBalance': '12345'},
{'UserName': 'Steve', 'PIN': '0002', 'CheckingBalance': '12', 'SavingsBalance': '123'},]
def withdraw():
while "w":
for record in bank:
# checks for checking or savings account & amount to withdraw
account = input("CHECKING (C) OR SAVINGS (S): ").lower
amount = int(input("AMOUNT FOR WITHDRAWAL: "))
# checks for enough balance and negatives for checking account
if account == "c":
if amount > record['CheckingBalance']:
amount = input("INVALID. PLEASE CHOOSE A DIFFERENT AMOUNT: ")
elif amount <= 0:
amount = input("INVALID. PLEASE CHOOSE A DIFFERENT AMOUNT: ")
else:
print("WITHDRAWAL SUCCESSFULLY COMPLETED.")
break
#this is part of the withdraw method and for some reason when I'm comparing the amount and record['CheckingBalance'] or record['SavingsBalance'], it doesn't work.
def deposit():
while "d":
# checks for checking or savings account & amount to deposit
account = input("CHECKING (C) OR SAVINGS (S): ").lower
amount = int(input("AMOUNT TO DEPOSIT: "))
# checks for 0 and negatives for checking account
if account == "c":
if amount <= 0:
print(input("INVALID. PLEASE CHOOSE A DIFFERENT AMOUNT: "))
else:
print("DEPOSIT SUCCESSFULLY COMPLETED")
break
# checks for 0 and negatives for savings account
if account == "s":
if amount <= 0:
print(input("INVALID. PLEASE CHOOSE A DIFFERENT AMOUNT: "))
else:
print("DEPOSIT SUCCESSFULLY COMPLETED")
break
#this is the deposit method
#both of these methods, I'm having a bug where after I input an amount, it prompts me to "CHECKINGS (C) OR SAVINGS(S) for some reason.
Your dictionaries contain strings instead of ints. Try changing
bank = [
{'UserName': 'Bob', 'PIN': '0001', 'CheckingBalance': '1234', 'SavingsBalance': '12345'},
{'UserName': 'Steve', 'PIN': '0002', 'CheckingBalance': '12', 'SavingsBalance': '123'},]
to
bank = [
{'UserName': 'Bob', 'PIN': '0001', 'CheckingBalance': 1234, 'SavingsBalance': 12345},
{'UserName': 'Steve', 'PIN': '0002', 'CheckingBalance': 12, 'SavingsBalance': 123},]
In addition, with while "w": and while "d": you have created while True loops (endless loops) and I don't see any breaks of these loops.

Resources