Python|转录字典键
在处理数据时,我们可能会遇到我们希望执行的各种数据相互转换。这些可以是将字典列表中的键转录到外部以进行概括。这种类型的实用程序非常有用。让我们讨论可以执行此操作的某些方式。
方法#1:使用字典理解
这个特定的任务可以使用字典理解的方法来执行,在这种方法中,我们从所需的列表中分配键和值并重新制作字典。
# Python3 code to demonstrate
# Dictionary key transcription
# dictionary comprehension
# initializing list
test_list = [{'state' : 'Haryana', 'capital' : 'Chandigarh', 'area' : 'North'},
{'state' : 'Karnataka', 'capital' : 'Bengaluru', 'area' : 'South'}]
# printing original list
print("The original list : " + str(test_list))
# using Dictionary comprehension
# Dictionary key transcription
res = { sub["state"]: {"capital": sub["capital"], "area": sub["area"] }
for sub in test_list }
# print result
print("The Dictionary after transcription of key : " + str(res))
The original list : [{‘capital’: ‘Chandigarh’, ‘state’: ‘Haryana’, ‘area’: ‘North’}, {‘capital’: ‘Bengaluru’, ‘state’: ‘Karnataka’, ‘area’: ‘South’}]
The Dictionary after transcription of key : {‘Haryana’: {‘capital’: ‘Chandigarh’, ‘area’: ‘North’}, ‘Karnataka’: {‘capital’: ‘Bengaluru’, ‘area’: ‘South’}}
方法 #2:使用字典理解 + items() + get()
也可以使用一组函数来执行此任务。这种方法允许灵活地添加任何选择的键。这在事先不知道密钥的情况下很有用。
# Python3 code to demonstrate
# Dictionary key transcription
# dictionary comprehension + items() + get()
# initializing list
test_list = [{'state' : 'Haryana', 'capital' : 'Chandigarh', 'area' : 'North'},
{'state' : 'Karnataka', 'capital' : 'Bengaluru', 'area' : 'South'}]
# printing original list
print("The original list : " + str(test_list))
# using dictionary comprehension + items() + get()
# Dictionary key transcription
res = {sub.get('state'): {key: val for key, val in sub.items()
if key != 'state'} for sub in test_list}
# print result
print("The Dictionary after transcription of key : " + str(res))
The original list : [{‘capital’: ‘Chandigarh’, ‘state’: ‘Haryana’, ‘area’: ‘North’}, {‘capital’: ‘Bengaluru’, ‘state’: ‘Karnataka’, ‘area’: ‘South’}]
The Dictionary after transcription of key : {‘Haryana’: {‘capital’: ‘Chandigarh’, ‘area’: ‘North’}, ‘Karnataka’: {‘capital’: ‘Bengaluru’, ‘area’: ‘South’}}