![](/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.