2024-05-29 02:39:06 发布
网友
我有下面的字典,我想按顺序打印钥匙: [Name,Gender,Occupation,Location]
[Name,Gender,Occupation,Location]
{'Gender': 'Male', 'Location': 'Nizampet,Hyderabad', 'Name': 'Srikanth', 'Occupation': 'Data Scientist'}
有人能建议怎么做吗
您可以在创建字典时安排键的顺序
Python 3.7+In Python 3.7.0 the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec. Therefore, you can depend on it.
Python 3.7+
In Python 3.7.0 the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec. Therefore, you can depend on it.
old_dict = {'Gender': 'Male', 'Location': 'Nizampet,Hyderabad', 'Name': 'Srikanth', 'Occupation': 'Data Scientist'} new_dict = { "Name": old_dict["Name"], "Gender": old_dict["Gender"], "Occupation": old_dict["Occupation"], "Location": old_dict["Location"] } print(new_dict)
输出
{'Name': 'Srikanth', 'Gender': 'Male', 'Occupation': 'Data Scientist', 'Location': 'Nizampet,Hyderabad'}
如果您有一个预定的顺序来打印数据,请将该顺序存储在键列表中,并循环使用它们
data = { 'Gender': 'Male', 'Location': 'Nizampet,Hyderabad', 'Name': 'Srikanth', 'Occupation': 'Data Scientist' } print_order = [ 'Name', 'Gender', 'Occupation', 'Location', ] for key in print_order: print(f'{key}: {data[key]}')
输出:
$ python3 print_dict_in_order.py Name: Srikanth Gender: Male Occupation: Data Scientist Location: Nizampet,Hyderabad
您可以在创建字典时安排键的顺序
输出
如果您有一个预定的顺序来打印数据,请将该顺序存储在键列表中,并循环使用它们
输出:
相关问题 更多 >
编程相关推荐