I'm writing code with Python. I have defined a lot of dictionaries and a function. I use the dictionary in the function. The dictionary name is the parameter's in function .
I want to get user input which dictionary to use but I don't know how to do this. I tried to get the name of the dictionary with the name in the code line below but it didn't
name=input()
bank("name")
error is:
Traceback (most recent call last):
File "............", line 47, in <module>
banka("hesap")
File "...................", line 18, in banka
print("merhaba",hesap['ad'])
TypeError: string indices must be integers
It's this part of your code:
hesap['ad']
According to the error, hasep is a string, not a dictionary. So you can only put integers into the square brackets.
You could maybe do someting like this
dictionary1 = {}
dictionary2 = {}
user_input = input("Enter 'dictionary1' for dictionary 1 or enter 'dictionary2' for dictionary 2")
if user_input == "dictionary1":
bank(user_input)
elif user_input == "dictionary2":
bank(user_input)
else:
print("unknown command")
Also for your code, when you used the bank function, you put the variable 'name' in speech marks. If you want to input the variable name in the function bank, dont add speech marks. :)
Maybe try doing this:
dict1={...}
dict2={...}
def bank(x):
if x=="dict1":
usedict=dict1
elif x=="dict2":
usedict=dict2
else:
print("No dictionary found with input given")
## write your program using usedict
x=input("enter which dictionary to use")
bank(x)
Remember, if you want to use the dictionary usedict outside the function as well, use global usedict inside the function
Related
This is what I am supposed to do in my assignment:
This function is used to create a bank dictionary. The given argument
is the filename to load. Every line in the file will look like key:
value Key is a user's name and value is an amount to update the user's
bank account with. The value should be a number, however, it is
possible that there is no value or that the value is an invalid
number.
What you will do:
Try to make a dictionary from the contents of the file.
If the key doesn't exist, create a new key:value pair.
If the key does exist, increment its value with the amount.
You should also handle cases when the value is invalid. If so, ignore that line and don't update the dictionary.
Finally, return the dictionary.
Note: All of the users in the bank file are in the user account file.
Example of the contents of 'filename' file:
Brandon: 115.5
James: 128.87
Sarah: 827.43
Patrick:'18.9
This is my code:
bank = {}
with open(filename) as f:
for line in f:
line1 = line
list1 = line1.split(": ")
if (len(list1) == 2):
key = list1[0]
value = list1[1]
is_valid = value.isnumeric()
if is_valid == True
value1 = float(value)
bank[(key)] = value1
return bank
My code returns a NoneType object which causes an error but I don't know where the code is wrong. Also, there are many other errors. How can I improve/fix the code?
Try this code and let me explain everything on it because it depends on how much you're understanding Python Data structure:
Code Syntax
adict = {}
with open("text_data.txt") as data:
"""
adict (dict): is a dictionary variable which stores the data from the iteration
process that's happening when we're separating the file syntax into 'keys' and 'values'.
We're doing that by iterate the file lines from the file and looping into them.
The `line` is each line from the func `readlines()`. Now the magic happens here,
you're playing with the line using slicing process which helps you to choose
the location of the character and play start from it. BUT,
you'll face a problem with how will you avoid the '\n' that appears at the end of each line.
you can use func `strip` to remove this character from the end of the file.
"""
adict = {line[:line.index(':')]: line[line.index(':')+1: ].strip('\n') for line in data.readlines()}
print(adict)
Output
{' Brandon': '115.5', ' James': '128.87', ' Sarah': '827.43', ' Patrick': "'18.9"}
In term of Value Validation by little of search you will find that you can check the value if its a number or not
According to Detect whether a Python string is a number or a letter
a = 5
def is_number(a):
try:
float (a)
except ValueError:
return False
else:
return True
By Calling the function
print(is_number(a))
print(is_number(1.4))
print(is_number('hello'))
OUTPUT
True
True
False
Now, let's back to our code to edit;
All you need to do is to add condition to this dict..
adict = {line[:line.index(':')]: line[line.index(':')+1: ].strip(' \n') for line in data.readlines() if is_number(line[line.index(':')+1: ].strip('\n')) == True}
OUTPUT
{'Brandon': '115.5', 'James': '128.87', 'Sarah': '827.43'}
You can check the value of the dict by passing it to the function that we created
Code Syntax
print(is_number(adict['Brandon']))
OUTPUT
True
You can add more extensions to the is_number() function if you want.
You're likely hitting the return in the else statement, which doesn't return anything (hence None). So as soon as there is one line in your file that does not contain 2 white-space separated values, you're returning nothing.
Also note that your code is only trying to assign a value to a key in a dictionary. It is not adding a value to an existing key if it already exists, as per the documentation.
This should effectively do the job:
bank = {}
with open(filename) as file:
for line in file:
key, val = line.rsplit(": ", 1) # This will split on the last ': ' avoiding ambiguity of semi-colons in the middle
# Using a trial and error method to convert number to float
try:
bank[key] = float(val)
except ValueError as e:
print(e)
return bank
What's wrong with that code? When I run it tells me this:
Traceback (most recent call last):
line 24, in <module>
people.append(Dict)
AttributeError: 'str' object has no attribute 'append'
My code:
live = 1
while live == 1:
#reading Database
dataRead = open ("db.txt","r")
if dataRead.read() != " ":
dataRead.close()
people = open ('db.txt','r').read()
do = input ('What Do You Want ? (Search , add) :\n')
#add people
if do == 'add':
#Get The New Data
n_Name = input ('enter the new name:\n')
n_age = input ('enter the new age:\n')
#new Dict
Dict = {'Name:':n_Name,'age':n_age}
people.append(Dict)
#adding people to file
dataWrite = open ("db.txt","w")
dataWrite.write(str(people))
dataWrite.close()
live = 0
The problem is, on line 24, you try to append a dictionary to a string. When you read the db file, it read it as a string. Also the code is really messy and there are a lot better ways to do it. But that's besides the point, the append() method is for lists and the variable "people" is a string, according to your error output.
It says that people is str then it doesn't have an append method. You should just concatenate strings to get them together.
Do:
people += '<append string>'
Have in mind you are trying to append a dictionary to a string. This will throw TypeError cause those type of elements can't be concatenated that way. You should do first: str(dict) to concatenate them.
You're also using a reserved word like dict as a variable. Change it to my_dict or other allowed name.
I'm reading a json file with the structure below:
[{"id":1,"gender":"Male","first_name":"Andrew","last_name":"Scott","email":"ascott0#shutterfly.com","ville":"Connecticut"},
{"id":3,"first_name":"Mary","last_name":"Richards","email":"mrichards2#japanpost.jp","ville":"Minnesota"}]
So, as you can see in the second "line" the field "gender" it'is not present.I realize that because my code to read the file got wrong in this line.
my code:
import json
def jsonreader():
##Reader for json files
##Open files using json library
with open('cust_data.json') as file:
data = json.load(file)
resultlist = list()
for line in data:
print(line["id"],line["gender"])
I got the error:-
C:/xxxxx/x.py
1 Male
Traceback (most recent call last):
2 Female
File "C:/xxxxx/x", line 67, in <module>
jsonreader()
File "C:/xxxxx/x", line 56, in jsonreader
print(line["id"],line["gender"])
KeyError: 'gender'
Before answer guys, you should know that I have a method to define the default value in "gender", voila my method:
def definegender(x):
if x is None:
x = 'unknown'
return x
elif (x =='Male') or (x=='Female'):#not None:
return {
'Male':'M',
'Female': 'F'
}.get(x)
else:
return x
So, in this case, I could not use something like a default value reading the values because I need to send some value to my method.
Some one of you guys would know how should be the best way to read this kind of files when we have missing objects. Thanks
why not using a default value for your dictionary in dict.get?
print(line["id"],line.get("gender","unknown"))
And since you want to transform input further, you could nest two dict.get together, the first one with None as default value, and a new table, like this:
gender_dict = {"Male":"M", "Female":"F", None : "unknown"}
print(line["id"],gender_dict.get(line.get("gender")))
(note that you don't need your overcomplex gender conversion method anymore)
Although this already has a perfect answer, my point of view is that there can be alternatives too. So here it is:
for line in data:
try:
print(line["id"],line["gender"])
except KeyError:
print(line["id"],"Error!!! no gender!")
This is called ErrorHandling. Read the docs here:
https://docs.python.org/3.6/tutorial/errors.html
update: Do you mean this?
update2 corrected misstake
try:
gender = definegender(line["gender"])
except KeyError:
gender = definegender(None)
print(line["id"],gender)
update3: (for future purposes)
as .get() returns None by default the most simple solution would be
gender = definegender(line.get("gender"))
print(line["id"],gender)
Why not simplify this with an if-statement?
for line in data:
if "gender" in line:
print(line)
I'm trying to get an input from the user and put that input into the file in its proper location.
Here is what I have done so far ( Names.txt has a list of first names in alphabetical order and I don't want any duplicates so I converted list into set)
def main():
outfile = open("Names.txt","a")
list1 = []
name1 = 0
name1 = input("Enter a name, if you want to quit, enter q: ")
while name1 != "q":
list1 = list1.append(name1)
outfile.writelines(list1)
list1.sort()
s = set(list1)
return s
main()
but I am having a problem whenever I input something other than q.
Traceback (most recent call last):
File "C:\Users\SKKU\Desktop\1.py", line 12, in <module>
main()
File "C:\Users\SKKU\Desktop\1.py", line 8, in main
outfile.writelines(list1)
TypeError: 'NoneType' object is not iterable
What am I supposed to do about it?
Am I doing it right?
another pointer, there is no use in declaring name1 = 0
name1 = 0 #you can remove this
name1 = input("Enter a name, if you want to quit, enter q: ")
while name1 != "q":
list1 = list1.append(name1)
outfile.writelines(list1)
additionally, your while loop is writing lines to your file indefinitely,
You are indicating your program to append name1 to your list, then write something that makes no sense to your file as mentioned by #Blorgbeard
So there are several things you might want to rewrite/remove in your code.
you might want to consider reading a bit on List manipulations (http://effbot.org/zone/python-list.htm) and using a for loop :
list = [#items]
for item in list: #instead of a while loop
#do something
print item
The line to add a name to the list should be just:
list1.append(name1)
Because append modifies the existing list, and doesn't return anything (i.e. returns None).
Hence, you were setting list1 to None with list1 = list1.append(name1). Then you passed None to outfile.writelines, which tried to iterate over the thing you passed, which of course, doesn't make sense for None.
I'm fairly new to Python but am ok with programming (although haven't done any for about 5 years).
I've searched but can't find anything to answer my problem:
I have a number of lists, each with values in them, I'm trying to create a generic function that takes 2 values that searches a list, the 2 values are obviously the list name, and the string to search for in that list:
list0 = ["name","date","cat","dog"]
list1 = ["house","chair","table"]
list2 = ["tv","dvd","computer","mouse"]
usersearchlist = raw_input("Enter list name: ")
usersearchitem = raw_input("Enter item to search for: ")
def searchmemory(usersearchlist,usersearchitem):
return usersearchlist.index(usersearchitem)
I then call the function:
print "I found", searchmemory(usersearchlist,usersearchitem)
I'm getting the "ValueError: substring not found" because the function call is taking the literal string passed into the function and not referencing the value contained inside of it.
Hope that makes sense, am I doing something totally wrong?
try
lists = {"list0" : ["name","date","cat","dog"],
"list1" : ["house","chair","table"],
"list2" : ["tv","dvd","computer","mouse"]}
usersearchlist = raw_input("Enter list name: ")
usersearchitem = raw_input("Enter item to search for: ")
def searchmemory(usersearchlist, usersearchitem):
if (usersearchlist in lists and usersearchitem in lists[usersearchlist]):
return lists[usersearchlist].index(usersearchitem)
else:
return -1
This stores all the lists in a dictionary and checks if the value exists first so you shouldn't get a ValueError
I would prefer to put the lists in a dictionary similar to #SimplyKiwi 's answer.
Alternatively, you can also achieve it with globals():
print "I found", searchmemory(globals().get(usersearchlist, []), usersearchitem)
Be warned though in this case, you are implicitly giving the user access to all the global variables. In most scenario, this is not what you would want the users to be able to do.