How do I load in string values into dictionary with keys?

In Python 3 I’ve created an empty dictionary with the following keys:

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)

I don’t know how to load values from a string like this sequentially:

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

to obtain:

mydict = { 
    "Num": 1,
    "ID": LUC-TOR,
    "Cognome": Tortuga,
    "Data": 10/13/1991
    "Nome": Luca
    "Ruolo": 2
    "nick": Tortuga
    "V17": 33524.7

What is the best pythonic way to do it?


You could use 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 produces a sequence of tuple pairs, e.g. ('Num', '1'), ('ID', 'LUC-TOR'), …

If you wanted you could also have a list of types to convert the values to:

types = [int, str, str, date, ...]

mydict = {key: _type(value)
          for key, value, _type in zip(keys, values, types)}