Looping Through Values In Functions - python

so I need to loop through dictionaries of dictionaries in dictionaries. Basically I am saving information like this to a dictionary:
accounts = {}
def accountcreator():
newusername = raw_input()
newpassword = raw_input()
UUID = 0
UUID += 1
accounts[newusername] = {newpassword:UUID}
Then in another function I want to loop through all of these values, so for example this is what I have so far. This correctly loops through all of the newusernames.
def accounts():
for usernames in accounts:
#I do not know what to do from here on out
#I want it to loop through all of the newpasswords and UUID
#And the UUIDs would be saved to a new variable
Please help me, I just want a simple answer on how to loop through all of the values.
Thank You!
EDIT
So basically this is a example:
def accountcreator():
newusername = raw_input() #For raw input I put in cool-account-name
newpassword = raw_input() #For raw input I put in this-is-a-password
UUID = 0
UUID += 1
accounts[newusername] = {newpassword:UUID} #So basically what is being saved is accounts[cool-account-name] = {this-is-a-password:1}
So after that happens I want this to happen with the accounts function. I want it to print each separate item, so basically it would print each of the follow: username, password, and UUID. So supplied with the information above it would print Username: cool-account-name, Password: this-is-a-password, and the UUID: 1.

You just need to add another loop over the values of accounts[usernames]
def accounts():
for usernames in accounts:
for passwords in accounts[usernames]:
# Here you can access the UUID you want through: accounts[usernames][passwords]

Dictionaries work differently than lists, so you will have to use the .values() or .keys() to iterate.
accounts.keys() would return all the keys in a dictionary:
d = {1:2,3:4}
for v in d.keys():
print (v)
# Would print 1 and 3
# And
for v in d.keys():
print (d[v])
# Would print 2 and 4
accounts.values() would return all the values of those keys in a dictionary:
d = {1:2,3:4}
for v in d.values():
print (v)
# Would print 2 and 4
You also must put global accounts line in each function, so that it would be able to access the accounts variable defined from outside. Otherwise, each function would create its own accounts variable or give an error

Related

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

Python call function with list from loop

I have a function getloantype(account_no) which I would like to call. The account numbers are in a list ['10101-2','10101-2', '10101-3'] and I would like the function to run one by one through all the account numbers and put all the results into another list. However, I cannot seem to get my code to run.
What I do: first, I get the user to input his userID and use it to fetch all the bank accounts that he owns from SQL database:
userid = input("Please enter user id")
conn=create_connection()
def getacct(userid):
query = """\
select Account_Number
from User_Account
where UserID = '{}'
""" .format(userid)
return (execute_read_query (conn, query))
account_no = getacct(userid)
As such, the account numbers would end up being in a list [account_no]. Next, I will need to use the account number to fetch his Loan ID. From this part comes the first question. Am I supposed to code it as getloanid(account_no) or getloanid(x) whereby x is for x in account_no ?
def getloanid(x):
query = """\
select SUBSTRING(LoanID, 1, 2)
from Account_Delinquency
where Account_Number = '{}'
""" .format(account_no)
return (execute_read_query (conn, query))
From here, I assume that I should do a nested for loop but the way I coded it, the list remains empty.
loanlist = []
for i in account_no:
for x in i:
getloanid(x)
loanlist.append(i[0])
I have also tried this which would return error :
'NoneType' object is not iterable
mylist = []
loanlist = []
for i in account_no:
mylist.append(i[0])
for x in mylist:
a = getloanid(x)
for i in a:
loanlist.append(i[0])
How can I code it such that I can call the function getloantype(account_no) with all the account numbers in the list account_no = getacct(userid) and have all the results be appended into a new list [loanlist]?
It is not so clear the structure of your program, and data returned from functions, but if I can undestand, a possible simple solution could be somthing like this:
result_list = [getloantype(account_no) for account_no in account_list]

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.

Python Dictionaries with lists from user input how to solve this?

Write a program that ask the user to enter an integer representing the number of items to be added to the stock. For these items, the program should then ask for the item barcode number and name, add them to a dictionary and print them.
Why is my code not working as expected?
size=input("Enter size of list")
names=[input()]
code=[int(input())]
for i in size:
print("Enter name and code")
names.append(input())
code.append(int(input()))
dict={names[i]:code[i]}
print(dict)
This a functioning version of your code:
size = input("Enter size of list")
names = []
code = []
for i in range(int(size)):
print("Enter name and code")
names.append(input())
code.append(int(input()))
d = dict(zip(names, code))
print(d)
Among the errors that needed fixing:
Only use input() in your for loop when you need the data.
i needs to cycle through range(int(size)) rather than a string input.
Create the dictionary from your lists at the end via zip.
Do not name variables after classes, e.g. use d instead of dict.

Find an item in nested lists

A project in a coding class I'm taking asks students to finish the code for a password saver with a number of options and a menu. The part I'm having difficulty with is printing a password based on the website associated with it.
Passwords are saved in a list like so:
passwords = [["yahoo","XqffoZeo"],["google","CoIushujSetu"]]
What I'm attempting to do is find the address of an item within this list, inputted by the user, and print the item directly after it. The user will be asked to input a website and the following item in the list (the password) will be printed.
However, for testing purposes, I also need to check to see if a password for the website in question is in the "passwords" list.
if passwordToLookup in passwords:
print(passwords.index(passwordToLookup))
For some reason, this always returns "False." Is this because the list I'm searching is encrypted? If so, how can I search in this list for a specific item? How could I print the second item in the list following the website?
Using dictionaries
# convert list into dictionary
d = dict(tuple(passwords))
try:
d[passwordToLookup]
except KeyError:
# what to do if no password available
else:
# what to do if available
or use default get method of dictionary
return d.get(passwordToLookup, default=None)
Without dictionaries
values = list(zip(*passwords))
try:
the_password = values[1][values[0].index(passwordToLookup)]
except ValueError:
# what to do if no password available
else:
# what to do if available
You can loop through the list and check for the website:
for elem in passwords:
if passwordToLookup in elem:
print # elem[0] for the website or elem[1] for the password
not sure why you are trying to print the index but you can also use passwords.index(elem) if you want it.
Your problem is that you are currently only looking in passwords which is a list of lists, but you need to iterate through passwords and test the individual lists within it. You could use something like this
passwords = [["yahoo","XqffoZeo"],["google","CoIushujSetu"]]
def getPasswordIndex():
for list in passwords:
if "CoIushujSetu" in list:
return list.index("CoIushujSetu")
else:
print(False)
print(getPasswordIndex())
#returns False then 1 so it's the second item in the second list """
print(passwords[1][1])
#prints "CoIushujSetu"
Use a dictionary (key: value pairs) and your code will be as simple as this:
passwords = [["yahoo","XqffoZeo"],["google","CoIushujSetu"]]
pass_dict = dict(passwords)
site = input("Insert site: ")
if site in pass_dict: # searching only in keys
print(pass_dict[site]) # print value of that key
What you need to do is iterate through the list something like this :
def ifPassExist():
for password in passwords:
if passwordToLookUp in password:
return passwords.index(password)

Categories

Resources