![](/img/trans.png)
[英]How can I print 3 different types of values in a sorted 2d list from a text file?
[英]How do I print a sorted list of a dictionary from a text file?
所以这个数据文件叫做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)为键的字典,值是电话号码和生日的列表(即。{'John': (555-234-9876, May 5)} .但是,我不确定如何排序(按键值)并一个接一个地打印出文本文件的每一行.目标output是:
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
我将如何使键(名称)正确排序和迭代? 任何帮助,将不胜感激!
尝试这个:
for name in sorted(myfriends):
print("{} {} {}".format(name, myfriends[name][0], myfriends[name][1].strip("\n")))
您正在迭代您创建的myfriends
字典的键。 您需要使用此键来访问包含您之前存储的字段的字典条目:
for key in sorted(myfriends):
print("{} {} {}".format(key, myfriends[key][0], myfriends[key][1]))
将条目存储到字典中时,您使用fields[0]
作为键,因此您应该将output key
到output名称,然后访问myfriends[key][0]
和myfriends[key][1]
到Z748E6221F6391F63913成为fields[1:]
。
让我知道这是否有帮助:
file_name = "friends.txt"
friends = []
meta_data = ['name', 'phone', 'dob']
with open(file_name,"r") as f:
for friend in f.readlines():
friend_attr = friend.strip().split(",")
friends.append(dict(zip(meta_data, friend_attr)))
sorted_friends = sorted(friends, key=lambda k: k['name'])
for f in sorted_friends:
print("{0},{1},{2}".format(f['name'], f['phone'], f['dob']))
Output:
➜ Desktop python stack.py
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.