Python – 更改字典列表中键的类型
有时,在处理数据时,我们可能会遇到需要更改字典列表中特定键值的类型的问题。这类问题可以在数据域中应用。让我们讨论可以执行此任务的某些方式。
Input : test_list = [{‘gfg’: 9, ‘best’: (7, 2), ‘is’: ‘4’}, {‘is’: ‘2’}]
Output : [{‘gfg’: 9, ‘best’: (7, 2), ‘is’: 4}, {‘is’: 2}]
Input : test_list = [{‘is’ : ‘98393’}]
Output : [{‘is’ : 98393}]
方法#1:使用循环
这是解决此问题的蛮力方法。在此,我们迭代所有列表元素和字典键,并将所需的字典键的值转换为所需的类型。
# Python3 code to demonstrate working of
# Change type of key in Dictionary list
# Using loop
# initializing list
test_list = [{'gfg' : 1, 'is' : '56', 'best' : (1, 2)},
{'gfg' : 5, 'is' : '12', 'best' : (6, 2)},
{'gfg' : 3, 'is' : '789', 'best' : (7, 2)}]
# printing original list
print("The original list is : " + str(test_list))
# initializing change key
chnge_key = 'is'
# Change type of key in Dictionary list
# Using loop
for sub in test_list:
sub[chnge_key] = int(sub[chnge_key])
# printing result
print("The converted Dictionary list : " + str(test_list))
The original list is : [{‘is’: ’56’, ‘gfg’: 1, ‘best’: (1, 2)}, {‘is’: ’12’, ‘gfg’: 5, ‘best’: (6, 2)}, {‘is’: ‘789’, ‘gfg’: 3, ‘best’: (7, 2)}]
The converted Dictionary list : [{‘is’: 56, ‘gfg’: 1, ‘best’: (1, 2)}, {‘is’: 12, ‘gfg’: 5, ‘best’: (6, 2)}, {‘is’: 789, ‘gfg’: 3, ‘best’: (7, 2)}]
方法#2:使用列表推导
也可以使用列表推导作为速记来执行此任务。在此,我们使用相同的方法以更短的方式迭代列表。
# Python3 code to demonstrate working of
# Change type of key in Dictionary list
# Using list comprehension
# initializing list
test_list = [{'gfg' : 1, 'is' : '56', 'best' : (1, 2)},
{'gfg' : 5, 'is' : '12', 'best' : (6, 2)},
{'gfg' : 3, 'is' : '789', 'best' : (7, 2)}]
# printing original list
print("The original list is : " + str(test_list))
# initializing change key
chnge_key = 'is'
# Change type of key in Dictionary list
# Using list comprehension
res = [{key : (int(val) if key == chnge_key else val)
for key, val in sub.items()}
for sub in test_list]
# printing result
print("The converted Dictionary list : " + str(res))
The original list is : [{‘is’: ’56’, ‘gfg’: 1, ‘best’: (1, 2)}, {‘is’: ’12’, ‘gfg’: 5, ‘best’: (6, 2)}, {‘is’: ‘789’, ‘gfg’: 3, ‘best’: (7, 2)}]
The converted Dictionary list : [{‘is’: 56, ‘gfg’: 1, ‘best’: (1, 2)}, {‘is’: 12, ‘gfg’: 5, ‘best’: (6, 2)}, {‘is’: 789, ‘gfg’: 3, ‘best’: (7, 2)}]