Index of dictionary to another dictionary - python

hey I have been trying to get this value from one dictionary and use it as a key with another dictionary. and I get keyError
userID = some input lets say 364853
BALANCE = {540997: 10500, 266732: 50000}
ACCOUNTS = {364853: 540997, 266732: 540922}
and I'm trying to print:
print(ACCOUNTS[BALANCE[userId]])
and i get keyError( 364853 )

You have your references backwards. Let's do this in order. You have a userID; you need to get the account number. First, if this is the straight user input -- a string, rather than the int you show in your code and error message -- then you must convert it. Then you look it up in ACCOUNTS:
acct_no = ACCOUNTS[int(userID)]
Now, you use the account number to get the balance:
user_bal = BALANCE[acct_no]
In this statement, using simple algebraic substitution:
user_bal = BALANCE[ACCOUNTS[userID]]
See how that works? In English, this reads as "I want the balance of the account of the userID".

Related

Using a key taken from an input and using it to recall a value

The project is based on a cashier. When an input is accepted, it gets stored. I have used this to determine whether an item is in the dictionary or not.
I am currently stuck on how to implement the input as a key to recall the corresponding value in a defined dictionary.
Is there any way to do this using the tools I've used, or is a more complicated function required? My code is underneath, and the very last line seems to be the problem. Thanks.
my_dictionary = {"Chips", 1}
#Taking order
order = input("What do you want? \n")
#Recalling order
if order in my_dictionary:
print(f"Okay you want {order}")
else:
print("We dont have that please leave")
exit()
#Gving price
print(my_dictionary["order"])
Below is the code I have written that checks if the order the user inputs is:
In your dictionary.
In stock.
Python is case sensitive so I have added the .title() method to the user input to convert the string to title case. This is because the 'Chips' in your dictionary is also in title case.
my_dictionary = {
"Chips" : 1
}
order = input("What do you want?\n").title()
if order in my_dictionary:
if my_dictionary[order] == 0:
print("We don't have that, please leave.")
else:
print(f"Okay you want, {order}")
Hopefully this helps :)
remove the " " around order like: my_dictionary[order] in your last print() function.
I've opted to use this code for the time being, having solved the issue:
my_dictionary = {"chips", 1}
order = input("What do you want?\n").lower()
if order in my_dictionary:
print(f"Ok you want {order}")
else:
print("We dont have that, leave")

how do i match if value match my dictionary in python

I'm super new to python so i don't know anything even the basics of basics function so could anyone tell me how do i match value to my dictionary and where did i do wrong
#dictionary
id = {"2":"30", "3":"40"}
#json display from web
messages: {"id":2,"class":0,"type":1,"member":"N"}
if messages['id'] == id: # << this part i think i'm doing it wrong too because it prints error`
print ('the new id value from dictionary') # << what do i put in here`
else:
print ('error')
Use if str(messages['id']) in id instead of if messages['id'] == id
to check if a values is a key in a dict you can do it like this:
if messages['id'] in id:
but it will not work right away in your case.
The values in the json data are integers so you need to convert them to match the dict.
you will end up with this
if str(messages['id']) in id:
full code:
id = {"2": "30", "3": "40"}
messages = {"id":2,"class":0,"type":1,"member":"N"}
if str(messages['id']) in id:
print(id[str(messages['id'])])
else:
id[str(messages['id'])] = '50'
The error occurs because you need to use an = to assign variables:
messages = {"id":2,"class":0,"type":1,"member":"N"}
instead of
messages: {"id":2,"class":0,"type":1,"member":"N"}
Concerning what you want to achieve, you are trying to access a dictionary value by using a default value ("error") in case the key doesn't exist. You can use dict.get for that, rather than if-else:
#dictionary
id_dict = {"2":"30", "3":"40"}
#json display from web
messages = {"id":2,"class":0,"type":1,"member":"N"}
print(id_dict.get(messages['id'], "error"))
Caveats:
Don't use id as a variable name, as it is a Python built-in keyword.
If the id_dict has string keys, you also need to use strings to access it, i.e. messages = {"id":2 ... will not give you the value "30" for id_dict = {"2":"30", "3":"40"}.
You need to convert the value to check to string in order to perform a valid comparison. Also, you should not use Python keywords as name variables to avoid additional issues:
id_dict = {"2":"30", "3":"40"}
#Use = to assign variables, not :
messages = {"id":2,"class":0,"type":1,"member":"N"}
if str(messages['id']) in id_dict:
print ('the new id value from dictionary')
else:
print ('error')
Output:
the new id value from dictionary

making a function to retrieve information from a key in a dictionary

I am a newbie programmer so sorry if any of these are dumb questions. This class is my first ever programming experience.
I am trying to create a search function that will search a dictionary and upon invoking it would give you all the keys from the dictionary separated by a '/t'. I then want to make the function prompt the user to enter a key. When the key is in the dictionary the key is supposed to give you the the information from the dictionary. When the key is not in the dictionary I want to create an output message such as "That student is not in class".
I have created a function off of my dictionary which will simply print all the information from the dict if you enter the correct key; however it is not off of the search function. I know I am lacking in having a true/except block that works, and a while true and return function.
I need to make (searchStudentDict) or use a true/except block or while true or a return statement. Below is my incorrect code trying to do this problem within it's boundaries.
def searchStudentDict():
for i in dctStudents.keys():
try:
while true:
except:
print('That student is not in class')
return
searchStudentDict(dctStudents)
I would be forever grateful to anyone who could edit this and get this to actually show up in the code block I've spent more time formatting than on my question. It isn't taking any of the indents i made
The expected output is the keys below tab separated such as
7373'\t'8274'\t'9651'\t'2213'\t'8787'\t'9999
*using python create tab here since the physical tab key will not tab them apart.
dctStudents = {
'7373':['Walter White',52,'Teacher'],
'8274':['Skyler White',49,'Author'],
'9651':['Jesse Pinkman',27,'Student'],
'2213':['Saul Goodman',43,'Lawyer'],
'6666':['Gus Fring',54,'Chicken Guy'],
'8787':['Kim Wexler',36,'Lawyer'],
'9999':['Tuco Salamanca',53,'Drug Lord'] }
One possible solution that may work for you:
#First print all the keys separated by tabs
print('\t'.join(someDict.keys()))
#Infinite loop
while True:
#read user input
userinput = input("Enter a key: ")
#the method get will try to get the key, if no matches will display the string passed.
print(someDict.get(userinput, "No key matches the dict"))
You can use * unpacking with sep argument of print:
print(*dctStudents, sep='\t')
When inside a function, this looks like:
def searchStudentDict():
print(*dctStudents, sep='\t')
...will print keys of the dictionary separated by tab space.
You can do following to retrieve value of a key if its present or throw a message if it's not present:
def searchStudentDict():
print(dctStudents.get(input('Enter key: '), 'That student is not in class'))
Something like this will display all of the keys from the dictionary separated by tabs
print('\t'.join(someDict.keys()))
If you want to search the dictionary for a specific key and print out the value that corresponds to that key while guarding against exceptions, the basic example is one way of doing so:
def searchStudentDict(someDict):
targetKey = ""
# End at user's request
while True:
targetKey = input("Enter a student ID (\'q\' to quit): ")
if targetKey.lower() == 'q':
break
# Search for it in dictionary using try-except (handle exceptions)
try:
print("Student {} Info: {}".format(targetKey, someDict[targetKey]))
except KeyError:
print("No information exists for this student")
except:
print("Some unknown error occurred")
# Handle how you see fit
print('Ending search...')
def main():
studentDict = {
'7373' : ['Walter White',52,'Teacher'],
'8274' : ['Skyler White',49,'Author'],
'9651' : ['Jesse Pinkman',27,'Student'],
'2213' : ['Saul Goodman',43,'Lawyer'],
'6666' : ['Gus Fring',54,'Chicken Guy'],
'8787' : ['Kim Wexler',36,'Lawyer'],
'9999' : ['Tuco Salamanca',53,'Drug Lord']
}
# Print the existing students
print('\t'.join(studentDict.keys()))
# Perform search
searchStudentDict(studentDict)
if __name__ == "__main__":
main()
And the corresponding output would be:
$ py -3 search.py
7373 8274 9651 2213 6666 8787 9999
Enter a student ID ('q' to quit): 8274
Student 8274 Info: ['Skyler White', 49, 'Author']
Enter a student ID ('q' to quit): 9999
Student 9999 Info: ['Tuco Salamanca', 53, 'Drug Lord']
Enter a student ID ('q' to quit): 1111
No information exists for this student
Enter a student ID ('q' to quit): q
Ending search...
Typically, you would not want to handle a search inside a dictionary this way (using try-except). A simple if statement or the use of get should suffice but if you require the use of a try-except, you would need to guard against the KeyError that would be raised if you try to access a key that does not exist. Hope this helps.

Dictionary entry not working as intended, only last entry getting inserted-Python

Working on this for learning experience. The 3 ideas below I came up with
A) User creates a profile so I have a dictionary for fname and lname.
B)Then I randomly generate userid add that to a list. This list only contains random user id that I will user later eg: userid012,userid89
C) I assign A and B in a new dictionary. Output looks like this:
used_id user3
profile {'lastname': 'jon', 'firstname': 'jme'}
problem: I only see the last values user id and names. If I have more than 2 entries, I do not see the 1st ones. Helpful hint would be really helpful.
Thank You.
import random
print('Enter choice 1-3:'),'\n'
print('', '1-Create new profile','\n',
'2-Update existing profile','\n',
'3-Delete a profile')
#global variables
choice=int(input())
user_directory={}
#Dictionary function that takes fst and lst name and puts in a dict:
def new_profile():
new_profile={}
fn=input('First name:')
new_profile['firstname']=fn
ln = input('Last name:')
new_profile['lastname'] = ln
for k,v in new_profile.items():
new_profile[k]=v
return new_profile
#Generates a random user id which we will assign to a user created above
def user_id():
uid_list=[]
user_id='user'+str(random.randint(0,101))
uid_list.append(user_id)
if(user_id in uid_list):
uid_list.remove(user_id)
user_id = 'user' + str(random.randint(0, 101))
uid_list.append(user_id)
return user_id
#This dictionary will have user id and associate created new_profile
def addToDict():
#user_directory={} unable to use this making it global
user_directory['used_id']=user_id()
user_directory['profile']=new_profile()
for key,value in user_directory.items():
user_directory[key]=value
return user_directory
if(choice==1):
# myuser=addToDict() this appraoch did not work
#addToDict>> adding it here will not get this option in while loop, put inside while
while True:
addToDict()
print('Add another entry?')
choice=input()
#Put the line below to see if number increases
print('Current', len(user_directory)-1)
if(choice!='stop'):
continue
else:
break
for k,v in user_directory.items():
print(k,v)
Bad indentation in the last line of new_profile(). The return is running on the first iteration. Try:
for k,v in new_profile.items():
new_profile[k]=v
return new_profile
Btw, you don't seem to be following most conventions/standards in Python. Take a look at this simple tutorial about PEP, the official style guide. This way you can make better looking code and we can help faster :)
Your code contains a couple of bugs. I can only guess what you want to do. Lets start with the obvious: The function addToDict() should probably add a new user to the dictionary.
What you usually want is to have a dictionary which maps a user_id onto a profile:
def addUserToDict(user_dictionary, user_id, profile):
user_directory[user_id] = profile
And then in the input loop below you call this function with your dictionary, a new user id and a new profile.
A second bug is in user_id(): You always return a list with one new element, with a new random user id. And you always discard the first generated user id and then you add a second one.

ArcMap Field Calculator Program to create Unique ID's

I'm using the Field Calculator in ArcMap and
I need to create a unique ID for every storm drain in my county.
An ID Should look something like this: 16-I-003
The first number is the municipal number which is in the column/field titled "Munic"
The letter is using the letter in the column/field titled "Point"
The last number is simply just 1 to however many drains there are in a municipality.
So far I have:
rec=0
def autoIncrement()
pStart=1
pInterval=1
if(rec==0):
rec=pStart
else:
rec=rec+pInterval
return "16-I-" '{0:03}'.format(rec)
So you can see that I have manually been typing in the municipal number, the letter, and the hyphens. But I would like to use the fields: Munic and Point so I don't have to manually type them in each time it changes.
I'm a beginner when it comes to python and ArcMap, so please dumb things down a little.
I'm not familiar with the ArcMap, so can't directly help you, but you might just change your function to a generator as such:
def StormDrainIDGenerator():
rec = 0
while (rec < 99):
rec += 1
yield "16-I-" '{0:03}'.format(rec)
If you are ok with that, then parameterize the generator to accept the Munic and Point values and use them in your formatting string. You probably should also parameterize the ending value as well.
Use of a generator will allow you to drop it into any later expression that accepts an iterable, so you could create a list of such simply by saying list(StormDrainIDGenerator()).
Is your question on how to get Munic and Point values into the string ID? using .format()?
I think you can use following code to do that.
def autoIncrement(a,b):
global rec
pStart=1
pInterval=1
if(rec==0):
rec=pStart
else:
rec=rec+pInterval
r = "{1}-{2}-{0:03}".format(a,b,rec)
return r
and call
autoIncrement( !Munic! , !Point! )
The r = "{1}-{2}-{0:03}".format(a,b,rec) just replaces the {}s with values of variables a,b which are actually the values of Munic and Point passed to the function.

Categories

Resources