Parsing a string entry into a tuple

Hi everyone.

So I have the following code fragments:

headers
['name', 'price', 'date', 'time', 'change', 'open', 'high', 'low', 'volume']
>>> row
['AA', '39.48', '6/11/2007', '9:36am', '-0.18', '39.67', '39.69', '39.45', '181800']
>>> types = [str, float, str, str, float, float, float, float, int]

With these, I perform some operations:

>>> converted = [func(val) for func, val in zip(types, row)]
>>> converted
['AA', 39.48, '6/11/2007', '9:36am', -0.18, 39.67, 39.69, 39.45, 181800]
>>> record = dict(zip(headers, converted))
>>> record
{'name': 'AA', 'price': 39.48, 'date': '6/11/2007', 'time': '9:36am', 'change': -0.18, 'open': 39.67, 'high': 39.69, 'low': 39.45, 'volume': 181800}

What my intention is now is to modify the above code so that the date entry is printed like a tuple: 'date': (6, 11, 2007).

The way to do that is this:
tuple([ int(vals) for vals in b.split('/') ]) where b is the date string.

How can I modify my code above so that I have the date in a tupled format in my record variable?

Replace b by using the get method with the date property of the the record dictionary.

1 Like

I was wondering if it’s doable when I converted the whole thing and created record. But this works just fine… thanks!

The simplest way to get the date would be:

tuple([ int(vals) for vals in row[2].split('/') ])

as long as the date is always the third value in the list of row.

1 Like