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)
示例输出(参见向下循环下一项时尝试):
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'}
这个问题是关于for循环的。在第一个for循环中,你可以看到我将用户输入的变量'name'与字典中的\ufeff昵称或名称进行比较,并打印出它是否已经存在于字典中。问题是我看不到下一步的方法,也就是对字典['name1']等等做同样的操作。当i = 0时,我做了一个while循环,然后在其中将其转换为字符串,并尝试连接字典变量,如if(response['name' + [i]]).lower()== name.lower():打印“person fullname already added”,但没有成功,因为它说我不能从列表中连接。我是一个初学者,我可能代码看起来很复杂,但任何建议或方法,从name0,name1等更改为使用\ufeff昵称数据,而不是每个字典标题将是有帮助的。
更新:这是我想到的到目前为止,它有点工作,但它卡住了,并结束了循环打印语句一遍又一遍:有什么解决办法吗?我觉得我什么都试过了。
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
1条答案
按热度按时间z31licg01#
从字典访问元素时,键可以是变量