import sys
import csv
import numpy as np
# CREATE A TEST DICTIONARY VARIABLE TO STORE ADDRESSES
address_dict = {'Harry' :
{'name' : 'Harry Potter',
'phone' : 'n/a',
'address' : '4 Pivet Drive Little Whinging, Surrey'}}
def add_person():
# USING A CSV FILE WILL NOT WORK IN THIS PROGRAM BECAUSE THE DICTIONARY IS IMPORT INSIDE A LIST. SAVE NeGaTiVe cOdE for future use. #
data = []
check_correct_args()
try:
with open(sys.argv[1]) as csvfile:
#with open('Address_Book.csv', "r") as csvfile:
reader = csv.DictReader(csvfile)
# reader = csv.reader(csvfile)
for row in reader:
data.append(row)
#return data
except FileNotFoundError:
sys.exit("Couldn't read csv file")
name = input('Type their fullname\n - ').strip()
dictA = {f'name{i}':v for i, v in enumerate(data)}
print(dictA)
for person in dictA:
response = dictA
if (response['name0']['name']).lower() == name.lower():
print("Person fullname already added")
elif (response['name0']['\ufeffnickname']).lower() == name.lower():
print("Person nickname already added")
for person in data:
#row = row 1
print("print row in data:",person)
SAMPLE OUTPUT:
project/ $python project.py Address_Book.csv after.csv
Would you like to add a new person to the address book? y/n
- y
Type their fullname
- Harry James potter
{'name0': {'\ufeffnickname': 'Harry', 'name': 'Harry James Potter', 'phone': 'N/A', 'address': '4 Pivet Drive Little Whinging, Surrey'}, 'name1': {'\uf
effnickname': 'Sirius', 'name': 'Sirius Black', 'phone': 'N/A', 'address': '12 Grimald Place London'}}
Person fullname already added
Person fullname already added
print row in data: {'\ufeffnickname': 'Harry', 'name': 'Harry James Potter', 'phone': 'N/A', 'address': '4 Pivet Drive Little Whinging, Surrey'}
print row in data: {'\ufeffnickname': 'Sirius', 'name': 'Sirius Black', 'phone': 'N/A', 'address': '12 Grimald Place London'}
The question is about the for loop. Inside the first for loop you can see me comparing the user inputted variable 'name' to the \ufeffnickname or name from the dictionary and printing out if it already exists inside the dictionary. The problem is i don't see a way to go to the next step which would be to do the same for dictionary ['name1'] and so on and so forth. I expiremented with making a while loop while i = 0 then inside of it converting it to a string and trying to concatenate the dictionary variable like if(response['name' [i]]).lower() == name.lower(): print 'person fullname already added' and no luck because its saying that i can't concatenate from a list. I am a beginner and i might code seem conveluted but any suggestions or a way to change from name0,name1 and soforth to using the \ufeffnickname data instead for each dictionary header would be helpful.
CodePudding user response:
When trying to get an element from a dictionary, the key can be a variable
sample_dict = {'name0': 'hello', 'name1': 'world'}
x = 'name0'
y = 'name1'
print(sample_dict[x])
# hello
print(sample_dict[y])
# world
CodePudding user response:
Thanks for the advice thusfar. This is what i came up with in the meantime: It kinda works but gets stuck in an infinite loop. You can figure the length of the dictionary is 2 from above because of 2 names. Any solutions?
import sys
import csv
import numpy as np
# CREATE A TEST DICTIONARY VARIABLE TO STORE ADDRESSES
address_dict = {'Harry' :
{'name' : 'Harry Potter',
'phone' : 'n/a',
'address' : '4 Pivet Drive Little Whinging, Surrey'}}
def add_person():
# USING A CSV FILE WILL NOT WORK IN THIS PROGRAM BECAUSE THE DICTIONARY IS IMPORT INSIDE A LIST. SAVE NeGaTiVe cOdE for future use. #
data = []
check_correct_args()
try:
with open(sys.argv[1]) as csvfile:
#with open('Address_Book.csv', "r") as csvfile:
reader = csv.DictReader(csvfile)
# reader = csv.reader(csvfile)
for row in reader:
data.append(row)
#return data
except FileNotFoundError:
sys.exit("Couldn't read csv file")
name = input('Type their fullname\n - ').strip()
dictA = {f'name{i}':v for i, v in enumerate(data)}
print(dictA)
count = (len(dictA) - 1)
while (count >= 0):
name_variable = 'name' str(count)
response = dictA
for person in dictA:
if (response[name_variable]['name']).lower() == name.lower():
print("Person fullname already added")
elif (response[name_variable]['\ufeffnickname']).lower() == name.lower():
print("Person nickname already added")
count -= count
for person in data:
#row = row 1
print("print row in data:",person)