gpt4 book ai didi

python - 如何从文本文件打印字典的排序列表?

转载 作者:行者123 更新时间:2023-12-04 09:49:44 33 4
gpt4 key购买 nike

所以这个数据文件叫做friends2.txt:

John,555-234-9876,May 5
Mary,556-987-2367,December 12
Albert,555-987-6765,June 12
Leo,555-789-9865,February 25
Ruth,555-786-1238,October 2
Fred,556-235-4536,June 17

但是,我必须创建字典,其中名称(即约翰)是键,值是电话号码和生日的列表(即{'John': (555-234-9876, May 5)} . 但是,我不确定如何排序(按键值)并逐行打印出文本文件的每一行。目标输出是:
Albert 555-987-6765 June 12
Fred 556-235-4536 June 17
John 555-234-9876 May 5
Leo 555-789-9865 February 25
Mary 556-987-2367 December 12
Ruth 555-786-1238 October 2

到目前为止,我的代码:
if __name__ == '__main__':
file_name = "friends2.txt"
inf = open(file_name,"r")

myfriends = {}
# how to build ? myfriends = {key, list(myfriends[name][0], myfriends[name])}
for line in inf:
fields = line.split(",")
myfriends[fields[0]] = fields[1:]

# value is a list containing the phone number, in position 0, and the birthday in position 1
# build a list from the phone number and birthday for the "value" in the key-value pair

for name in sorted(myfriends):
print("{} {} {}".format(sorted(myfriends), myfriends[name][0], myfriends[name][1].strip("\n")))

我试过
 for name in sorted(myfriends):
print("{} {} {}".format(sorted(myfriends), myfriends[name][0], myfriends[name][1].strip("\n")))

但这会产生
['Albert', 'Fred', 'John', 'Leo', 'Mary', 'Ruth'] 555-987-6765 June 12
['Albert', 'Fred', 'John', 'Leo', 'Mary', 'Ruth'] 556-235-4536 June 17
['Albert', 'Fred', 'John', 'Leo', 'Mary', 'Ruth'] 555-234-9876 May 5
['Albert', 'Fred', 'John', 'Leo', 'Mary', 'Ruth'] 555-789-9865 February 25
['Albert', 'Fred', 'John', 'Leo', 'Mary', 'Ruth'] 556-987-2367 December 12
['Albert', 'Fred', 'John', 'Leo', 'Mary', 'Ruth'] 555-786-1238 October 2

我将如何使键(名称)正确排序和迭代?
任何帮助,将不胜感激!

最佳答案

您正在迭代 myfriends 的键您创建的字典。您需要使用此键来访问包含您之前存储的字段的字典条目:

for key in sorted(myfriends):
print("{} {} {}".format(key, myfriends[key][0], myfriends[key][1]))


将条目存储到字典中时,您使用了 fields[0]作为键,所以你应该输出 key输出名称,然后访问 myfriends[key][0]myfriends[key][1]输出以前是 fields[1:] .

关于python - 如何从文本文件打印字典的排序列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62027305/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com