如何订购字典的键

2024-05-29 02:39:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的字典,我想按顺序打印钥匙: [Name,Gender,Occupation,Location]

{'Gender': 'Male',
 'Location': 'Nizampet,Hyderabad',
 'Name': 'Srikanth',
 'Occupation': 'Data Scientist'}

有人能建议怎么做吗


Tags: namedata字典顺序locationgender建议male
2条回答

您可以在创建字典时安排键的顺序

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

相关问题 更多 >

    热门问题