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)
Related
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
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()
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()
Below code i have used but not getting correct output.
def seek_keys(d, key_list):
newdict1 = dict([(vkey, vdata) for vkey, vdata in d.items() if(vdata) ])
dict1={}
for kk,vv in newdict1.items():
if kk in key_list:
dict1[kk]=[]
dict1[kk].append(vv)
print(dict1)
if isinstance(newdict1[kk], dict):
seek_keys(newdict1[kk], key_list)
filtered_list4 = ['Feature_Name', 'MY_username', 'started_my_time']
seek_keys(converted_xml,filtered_list4)
I'd like to return this:
{'Feature_Name[value]': {'MY_username':'value','started_my_time':'value'}
This is the dictionary i am using-
my_dict ={'1': {'Feature_Name': 'Lucky', 'usage_details_for_KD': 'No user details available_bye', 'use_percentage_file': '0%'}, '2': {'Feature_Name': 'Kunal', 'usage_details_for_KD': {'usage_details_for_KD_values': {'1': {'MY_description': 'for ' 'USER', 'started_my_time': '', 'MY_username': '1'}}}}, '3': {'Feature_Name': 'KD_M', 'usage_details_for_KD': {'usage_details_for_KD_values': {'1': {'MY_description': 'KD_DISPLAY ' '(0001)', 'started_my_time': 'Mon 12/23 ' '11:11', 'MY_username': 'KD_SI'}, '2': {'MY_description': 'Hello ' '0001)', 'started_my_time': 'Mon 12/23 ' '12:06', 'MY_username': 'Real_hero'}}}}, '4': {'Feature_Name': 'MY_NAME', 'usage_details_for_KD': {'usage_details_for_KD_values': {'1': {'MY_description': 'KD_DISPLAY ' '0001)',
'started_my_time': 'Mon 12/23 ' '13:57', 'MY_username': 'Same_hero'}}}}, '5': {'Feature_Name': 'Your_NAME', 'usage_details_for_KD': 'No user details available_bye', 'use_percentage_file': '0%'}}
Issue has been resolved, as i manage to solve.
class CoinBuilder_for_user_details:
def __init__(self,dict1,dict2):
self.Feature = dict2['Feature']
self.MY_username = dict1['MY_username']
self.started_my_time = dict1['started_my_time']
def main ():
max_key_all_f=max(converted_xml['Usages'])
for i in range(1,max_key_all_f+1):
if(ign not in converted_xml['Usages'][i]['usage_details_for_KD']):
print("\nFinal output is ")
max_key_user =(max(converted_xml['Usages'][i]['usage_details_for_KD']['usage_details_for_KD_values']))
if(type(max_key_user) == str):
A1=CoinBuilder_for_user_details(converted_xml['Usages'][i]['usage_details_for_KD']['usage_details_for_KD_values'],converted_xml['Usages'][i])
if(A1.statred not in null_v):
print("Feature Name : ",A1.Feature)
print("My User Name : ",A1.MY_username)
print("Date : ",A1.started_my_time)`enter code here`
i have dictionary as input an input like
Input dictionary :
{'location': {'street1': 'Deborah Throughway', 'city': 'East Betty', 'stateOrProvince': 'AK', 'postcode': '50545', 'country': 'US'}}
and expected output is:
'SiteAddress': 'Deborah Throughway, East Betty, AK, US, 50545'
I tried list(dictionary['location'].values()) but getting
{'SiteAddress': ['Deborah Throughway', 'East Betty', 'AK', '50545', 'US'] }
Please suggest what i am doing wrong and how we can get expected output
data = {'location': {'street1': 'Deborah Throughway', 'city': 'East Betty', 'stateOrProvince': 'AK', 'postcode': '50545', 'country': 'US'}}
def main():
loc = data['location']
address = ",".join([loc['street1'], loc['city'], loc['stateOrProvince'], loc['country'], loc['postcode']])
print("SiteAddress: {0}".format(address))
if __name__ == '__main__':
main()
output:
SiteAddress: Deborah Throughway,East Betty,AK,US,50545