为了账号安全,请及时绑定邮箱和手机立即绑定

如何在python字典中拆分值?

如何在python字典中拆分值?

慕尼黑的夜晚无繁华 2022-01-18 16:19:56
我有以列表形式存储的 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'}]在这里,在 keyLength中,我有两个值。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)我怎样才能使这成为可能...
查看完整描述

1 回答

?
叮当猫咪

TA贡献1776条经验 获得超12个赞

使用简单的迭代。


前任:


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'}]


查看完整回答
反对 回复 2022-01-18
  • 1 回答
  • 0 关注
  • 271 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号