我有以列表形式存储的dict值。 这就是它的样子:
d = [
{'Driveline': 'Rear-wheel drive', 'Hybrid': 'False', 'Classification': 'Automatic,Transmission', 'Number_of_Forward_Gears': 6, 'Fuel_Type': 'Gasoline', 'Length': 'first=prince,initial=p'},
{'Driveline': 'Rear-wheel drive', 'Hybrid': 'False', 'Classification': 'Automatic,Transmission', 'Number_of_Forward_Gears': 6, 'Fuel_Type': 'Gasoline', 'Length': 'first=steven,initial=s'}
]
在这里,在键Length
中,我有两个值。 first=steven,initial=s
我想拆分这些值并创建两个新字段,并将其以更新的形式存储在字典中。
必需的输出:
d = [
{'Driveline': 'Rear-wheel drive', 'Hybrid': 'False', 'Classification': 'Automatic,Transmission', 'Number_of_Forward_Gears': 6, 'Fuel_Type': 'Gasoline', 'Length': 'first=prince,initial=p','first':'prince','initial':'p'},
{'Driveline': 'Rear-wheel drive', 'Hybrid': 'False', 'Classification': 'Automatic,Transmission', 'Number_of_Forward_Gears': 6, 'Fuel_Type': 'Gasoline', 'Length': 'first=steven,initial=s','first':'steven','initial':'s'}
]
这是我尝试过的程序:
d = [
{'Driveline': 'Rear-wheel drive', 'Hybrid': 'False', 'Classification': 'Automatic,Transmission', 'Number_of_Forward_Gears': 6, 'Fuel_Type': 'Gasoline', 'Length': 'first=prince,initial=p'},
{'Driveline': 'Rear-wheel drive', 'Hybrid': 'False', 'Classification': 'Automatic,Transmission', 'Number_of_Forward_Gears': 6, 'Fuel_Type': 'Gasoline', 'Length': 'first=steven,initial=s'}
]
field_to_split = "Length"
split_using1 = ','
split_using2 = '='
b =[]
for i in d:
s = i[field_to_split].split(split_using1)
print(s)
b.append(s)
#print(s)
print(b)
我如何做到这一点...
答案 0 :(得分:3)
使用简单的迭代。
例如:
d = [
{'Driveline': 'Rear-wheel drive', 'Hybrid': 'False', 'Classification': 'Automatic,Transmission', 'Number_of_Forward_Gears': 6, 'Fuel_Type': 'Gasoline', 'Length': 'first=prince,initial=p'},
{'Driveline': 'Rear-wheel drive', 'Hybrid': 'False', 'Classification': 'Automatic,Transmission', 'Number_of_Forward_Gears': 6, 'Fuel_Type': 'Gasoline', 'Length': 'first=steven,initial=s'}
]
for i in d:
for j in i['Length'].split(","): #Split string by comma
i.update(dict([j.split("=")])) #Split string by eq sign and use dict() method to create a dictionary
输出:
[{'Classification': 'Automatic,Transmission',
'Driveline': 'Rear-wheel drive',
'Fuel_Type': 'Gasoline',
'Hybrid': 'False',
'Length': 'first=prince,initial=p',
'Number_of_Forward_Gears': 6,
'first': 'prince',
'initial': 'p'},
{'Classification': 'Automatic,Transmission',
'Driveline': 'Rear-wheel drive',
'Fuel_Type': 'Gasoline',
'Hybrid': 'False',
'Length': 'first=steven,initial=s',
'Number_of_Forward_Gears': 6,
'first': 'steven',
'initial': 's'}]