如何将字符串值加载到带键的字典中?



在Python 3中,我用以下键创建了一个空字典:

default_value = ''
sq = dict.fromkeys(['Num','ID','Cognome','Data','altezza','V6','spec_role','V8','Nome','Ruolo','nick','trasf','straniero','pict','V15','V16','V17'],default_value)

我不知道如何从这样的字符串顺序加载值:

line = '1   LUC-TOR Tortuga 10/13/1991              LUC-TOR Luca    2   Tortuga         33524.7 '

获得:

mydict = { 
"Num": 1,
"ID": LUC-TOR,
"Cognome": Tortuga,
"Data": 10/13/1991
"altezza":
"V6": 
"spec_role":
"V8":
"Nome": Luca
"Ruolo": 2
"nick": Tortuga
"trasf":
"straniero":
"pict":
"V15":
"V16":
"V17": 33524.7
}

最好的python方法是什么?

使用split()将字符串拆分为一个值列表。然后您可以将它与键列表组合。

keys = ['Num','ID','Cognome','Data','altezza','V6','spec_role','V8','Nome','Ruolo','nick','trasf','straniero','pict','V15','V16','V17']
my_dict = dict(zip(keys, line.split('t')))

您可以使用zip:

keys = ['Num','ID','Cognome','Data','altezza','V6','spec_role','V8','Nome','Ruolo','nick','trasf','straniero','pict','V15','V16','V17']
values = line.split('t')
mydict = dict(zip(keys, values))

zip产生一个元组对序列,如('Num', '1'),('ID', 'LUC-TOR'),…

如果你愿意,你也可以有一个类型列表来转换值:

types = [int, str, str, date, ...]
mydict = {key: _type(value)
for key, value, _type in zip(keys, values, types)}

使用zip()split():

keys = ['Num','ID','Cognome','Data','altezza','V6','spec_role','V8','Nome','Ruolo','nick','trasf','straniero','pict','V15','V16','V17']
mydict = dict(zip(keys, line.split('t')))

如果需要将行转换为数组,可以使用my func:

def convert_to_array(value):
result_line = ''
white_space_prev=False
for el in line:
if el!=' ':
if white_space_prev:
result_line+=' '+el
else:
result_line+=el
white_space_prev=False
else:
white_space_prev=True
return result_line.split(' ')
line = '1    LUC-TOR Tortuga 10/13/1991              LUC-TOR Luca    2   Tortuga         33524.7 '
print(convert_to_array(line))

结果:

['1', 'LUC-TOR', 'Tortuga', '10/13/1991', 'LUC-TOR', 'Luca', '2', 'Tortuga', '33524.7']

相关内容

  • 没有找到相关文章

最新更新