简体   繁体   English

我需要有关如何将字典元素保存到csv文件的帮助

[英]I need help on how to save dictionary elements into a csv file

I intend to save a contact list with name and phone number in a .csv file from user input through a dictionary. 我打算通过字典从用户输入中将名称和电话号码的联系人列表保存在.csv文件中。

The problem is that only the name is saved on the .csv file and the number is omitted. 问题是只有名称保存在.csv文件中,并且省略了该编号。

contacts={}
def phone_book():
   running=True
   while running:
    command=input('A(dd D)elete L)ook up Q)uit: ')
    if command=='A' or command=='a':
        name=input('Enter new name: ')
        print('Enter new number for', name, end=':' )
        number=input()
        contacts[name]=number
    elif command=='D' or command=='d':
        name= input('Enter the name to delete: ')
        del contacts[name]
    elif command=='L' or command=='l':
        name= input('Enter name to search: ')
        if name in contacts:
             print(name, contacts[name])
        else:
            print("The name is not in the phone book, use A or a to save")
    elif command=='Q' or command=='q':
        running= False
    elif command =='list':
        for k,v in contacts.items():
            print(k,v)
    else:
        print(command, 'is not a valid command')
def contact_saver():
  import csv
  global name
  csv_columns=['Name', 'Phone number']
  r=[contacts]
  with open(r'C:\Users\Rigelsolutions\Documents\numbersaver.csv', 'w') as f:
        dict_writer=csv.writer(f)
        dict_writer.writerow(csv_columns)
        for data in r:
            dict_writer.writerow(data)
phone_book()
contact_saver()

as I am reading your code contacts will look like 因为我正在阅读你的代码, contacts看起来就像

{
    'name1': '1',
    'name2': '2'
}

keys are the names and the value is the number. 键是名称,值是数字。

but when you did r = [contacts] and iterating over r for data in r that will mess up I guess your code since you are passing dictionary value to writerow instead of a list [name, number] 但是当你做了r = [contacts]并迭代r for data in r r for data in r时我会猜你的代码因为你将字典值传递给writerow而不是list [name,number]

You can do two things here. 你可以在这做两件事。 parse properly the contacts by: 通过以下方式正确解析联系人:

for k, v in contacts.items():
    dict_writer.writerow([k, v])

Or properly construct the contacts into a list with dictionaries inside 或者将联系人正确地构建到内部带有词典的列表中

[{
    'name': 'name1',
    'number': 1
}]

so you can create DictWriter 所以你可以创建DictWriter

fieldnames = ['name', 'number']
writer = csv.DictWriter(f, fieldnames=fieldnames)

...
# then you can insert by
for contact in contacts:
    writer.writerow(contact)  # which should look like writer.writerow({'name': 'name1', 'number': 1})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM