How do I create a dictionary from a file using Python? - python

Question: How do I open a file and turn it into my dictionary when I run the program?
So I created a test dictionary, saved it as .txt and .dat. Below I have entered the dictionary manually, but instead I want the program to open the file when ran, convert it to the dictionary, then continue into the functions.
(The overall objective of the program is to enter a key (productCode) to retrieve the product number, all of which works), but I want it to do it with the file, and not the manually entered data.
As always, guidance is appreciated!
file = open("test.dat", "r")
FILENAME = "test.dat"
# ------ Global Variables -------
d = {'ABCD': '0123', 'HJKL': '0987'}
user_cont = True
# ------- Functions -------
print("Product number finder.")
def get_productNum2():
global d
user_cont = True
while user_cont:
productCode = input("Enter an existing product code: ")
if productCode in d:
productNum = d[productCode]
print("Product #: " + productNum)
else:
print("Error finding product number; product code does not exist.")
user_cont = user_continue()
def user_continue():
global user_cont
prompt_user = input("Do you wish to continue? Enter y/n: ")
if prompt_user == "y":
user_cont = True
elif prompt_user == "n":
user_cont = False
return user_cont
# ------- Start Execution -------
get_productNum2()

You can (and should) write a dictionary to file in JSON format. Not only is it saved in a human-readable way, the JSON format also means the dictionary can even be loaded into many other programming languages and programs if needed!
Here is an example using the standard library package json:
import json
dict = {'ABCD': '0123', 'HJKL': '0987'}
dict_json = json.dumps(dict) #this line turns the dictionary into a JSON string
with open("my_dictionary.json", "w") as outfile:
outfile.write(dict_json)
Given a dictionary in JSON format, we can load it like this:
with open("my_dictionary.json", "r") as infile:
dict = json.load(infile)
Now you can access dict which you loaded from file as if it were the original dictionary:
>>> print(dict["ABCD"])
0123

Related

python dictionary with function and arguments

I want to use a dictionary to call functions with arguments, ie this simple program. I'm a very novice coder in python. what am I doing wrong?
output:
what name? : s
what name? : f
f
s
want to write or read? w/r:
w
want singers or band members? s/b:
s
1

code:
def addToFile(filename, lineString):
file = open(filename,"a")
file.write(lineString + "\n")
file.close()
return 1
def readFile(filename):
file = open(filename)
for line in file:
print(line)
file.close()
return 2
whatToDo = {
"ws": addToFile("band.txt",input("what name? : ")),
"wb": addToFile("singers.txt",input("what name? : ")),
"rs": readFile("singers.txt"),
"rb": readFile("band.txt")
}
def promptWrite():
print("want to write or read? w/r: ")
choice = str(input())
print("want singers or band members? s/b: ")
choice += str(input())
val = whatToDo[choice]
print(val)
promptWrite()
I didn't know If I needed to have a value or something, so I put the returns in the functions and had val. That isn't nessisary, I just drafted this up as an example program.
I know that you can have a dictionary with the names of the functions and call
dictionaryName[whateverthing]() to run the function, but I don't know how to have the arguments vary in that
You're calling the functions when you create the dictionary, not when you access the dictionary. Use lambda to create anonymous functions, then add () when you fetch from the dictionary to call it.
def addToFile(filename, lineString):
file = open(filename,"a")
file.write(lineString + "\n")
file.close()
return 1
def readFile(filename):
file = open(filename)
for line in file:
print(line)
file.close()
return 2
whatToDo = {
"ws": lambda: addToFile("band.txt",input("what name? : ")),
"wb": lambda: addToFile("singers.txt",input("what name? : ")),
"rs": lambda: readFile("singers.txt"),
"rb": lambda: readFile("band.txt")
}
def promptWrite():
print("want to write or read? w/r: ")
choice = input()
print("want singers or band members? s/b: ")
choice += input()
val = whatToDo[choice]()
print(val)
promptWrite()
You can't set functions with parameters to be executed in a dictionary, but you can store functions to call them after, with the corresponding dict key and parenthesis. Example:
my_dict['write_output'] = print
my_dict['write_output']('hello from my key')
IMHO, storing your functions in dict keys is a design incosistency. Dicts are mutable objects, then someone could overwrite your keys without any restriction and mess up your code everywhere. Not a good idea at all.

How to delete given element from a python dictionary?

I am practicing python and doing an exercise where I have to ask for input of different information from patients of a hospital (name, last name, etc) this information has to be saved in a different json file. I managed to do it however I also have to make it so, with an input, I can remove/edit a specific patient from the dictionary (along with all of their info) while keeping the others intact.
I was thinking that maybe I could assign a number to every patient that's added, so this patient can be tracked with the number, however I'm not sure how to code that. I did however made a function to clear everything from the json file, but it has to remove/edit someone specific, not everyone.
My code so far is:
import json
def read_file(file_name):
obj_arch = open(file_name, 'rt', encoding='utf-8')
str_contenido = obj_arch.read()
res = json.loads(str_contenido)
obj_arch.close()
return res
def save_file(file_name, lista):
obj_arch = open(file_name, 'wt', encoding='utf-8')
str_content_to_save = json.dumps(lista)
print(str_content_to_save)
obj_arch.write(str_content_to_save)
obj_arch.close()
opcion = int(input("choose an option: 1 - read. 2 - save"))
if opcion == 1:
lista = read_file('prueba_json.json')
print("Full list:")
print(lista)
else:
lista = read_file('prueba_json.json')
while True:
print("--- PATIENT INFO ---")
Name = input("Input name: ")
Lastname = input("Input lastname: ")
DateB= input("Input date of birht: ")
repeat = input("Do you want to add more info?: ")
clean_file = input("Clean everything from the json file? (yes/no): ")
lista.append({
"Name": Name,
"Lastname": Lastname,
"Date of Birth": DateB
})
if repeat == 'no' or repeat == 'NO':
break
save_file('prueba_json.json',lista)
With this I was able to sabe the patients info in the json file, but how can I write another input like "Insert number of patient to remove or delete" to do that?
In order to clean the whole json file I've done it with this:
def clean_json():
with open('prueba_json.json', 'w') as arc:
arc.writelines(["[{}]"])
if clean_file == "yes" or clean_file == "YES":
clean_json()
Maybe I could adapt some of this to remove or delete someone instead of the whole file?

Unable to write condition to update dictionary value in python

Please help! How can I write condition in my existing code which will check as below. Please look commented block. I can't append value in the dictionary/list. What do I need to write/change?
When user come back to main menu and run encryption process again using same key file but save the encrypted file in different name. User can create as many encrypted file using same key.
My try:
import Encrypt
from collections import defaultdict
key_value_dict = {}
def encrypt_file():
try:
txtfile = input("Your plain txt file that you want to encrypt : ")
encrypt_file = input("Directory to save the encrypted file : ")
key = input("Key for encryption : ")
# process for encryption
Encrypt.encrypt_file(txtfile, encrypt_file, key)
# ----------------------------------------------------------------
key_value_dict = defaultdict(list, {key: encrypt_file})
print(key_value_dict)
key_value_dict [key].append(encrypt_file)
print(key_value_dict )
# --------------------------------------------------------------------
except FileNotFoundError:
print("File Not Found!")
def menu():
selection = True
while selection:
print("""
MAIN MENU:
[1] Encrypt files using existing keys.
[2] Exit.
""")
try:
selection = input("Please select : ")
if selection == "1":
encrypt_file() # call function
elif selection == "2":
print("\n[4] Keys are used for encryption:", "\n", key_value_dict)
selection = None
else:
print("\n Invalid selection! Try again")
except ValueError:
print("\n Exception: Invalid user input!")
# Main function
if __name__ == '__main__':
menu()
If I understand correctly I don't think you need defaultdict
Try this:
# define this first outside the function like you have
encrypt_key_value_dict = {}
# Within your code block, get rid of the assignment to default dict
if encrypt_key_value_dict[key]:
encrypt_key_value_dict.append(encrypt_file)
else:
encrypt_key_value_dict[key] = [encrypt_file]
I can't see from your code where you keys are getting passed etc but I am sure you can figure that out.

PYTHON - File I/O with JSON objects [duplicate]

This question already has answers here:
Using global variables in a function
(25 answers)
Closed 4 years ago.
The problem that I am running into is that 'data' variable is not being set whenever I try to read in the json object. I only get an empty set. Below I have the code and the outputs.
import json
data = []
def add(name, amt):
data.append({"ticker": name, "amount": amt})
def write():
with open('portfolio.json', 'w') as file:
json.dump(data, file)
def load():
with open('portfolio.json', 'r') as file:
data = json.load(file)
def main():
choice = input("Do you want to add vals? (y/n): ")
if choice == 'y':
add('btc', 43.2)
add('xrp', 256.5)
add('xmr', 655.3)
print(data)
write()
if choice == 'n':
load()
print(data)
main()
Output 1:
Do you want to add vals? (y/n): y
[{'ticker': 'btc', 'amount': 43.2}, {'ticker': 'xrp', 'amount': 256.5}, {'ticker': 'xmr', 'amount': 655.3}]
Press any key to continue . . .
So now the file 'portfolio.json' contains the json object with all of the data, correct? So, now when I try to read that in, this is what I get:
Output 2:
Do you want to add vals? (y/n): n
[]
Press any key to continue . . .
As you can see, the data variable is just an empty set, and it is not taking in the data. However, if I were to go inside the load function and print out the data variable, I would get my value.
You need to add a return statement in your load function and store the result in data variable before printing it.
Ex:
def load():
with open(filename, 'r') as file:
return json.load(file)
def main():
choice = input("Do you want to add vals? (y/n): ")
if choice == 'y':
add('btc', 43.2)
add('xrp', 256.5)
add('xmr', 655.3)
print(data)
write()
if choice == 'n':
data = load()
print(data)

Python error list index out of range when reading from CSV

Hey I am trying to read data from a list that is from a CSV file
def Load(): #Loads data from the csv that can be stored in functions
global userdata
global user
userdata = []
f = open('userdata.csv','r')
data = csv.reader(f)
for row in data:
user = []
for field in row:
user.append(field)
userdata.append(user)
f.close()
This is the login function which I am looping over
def Login(): #Login function
global userdata
Load()
global user
print('Please now login to your account')
x = False
while x == False:
usernameLog = input('Please enter your username: ')
j = len(userdata)
for i in range(0,j):
if usernameLog == userdata [i][0]: #Validates username
print('Username accepted')
time.sleep(1)
My program successfully writes to the CSV but just doesn't read from it without throwing out this error. I might just be being stupid though.
You have the line user = [] inside the for loop, so you are always "cleaning" user before appending the new value, so only the last value is added, and the previous one is removed.
You should take it out of the loop, the same you are doing with userdata.
(This is what it looks like, unless your csv structure is totally different and you don't need one user per one userdata)

Categories