[Tutor] what am I not understanding?

Peter Otten __peter__ at web.de
Mon Oct 20 10:30:47 CEST 2014


Clayton Kirkwood wrote:

> raw_table = ('''
> a: Ask    y: Dividend Yield
> b: Bid     d: Dividend per Share
> b2: Ask (Realtime)           r1: Dividend Pay Date
> b3: Bid (Realtime)            q: Ex-Dividend Date
> p: Previous Close
> o: Open''')

> o: Open                                #why aren't both the \t and \n
> being removed? (tried with and without the square brackets)

> I am trying to get to where I can create a dict using the ':' separator

You never state your actual problem with sufficient precision, so I'm going 
to assume:

- Create a Python dict from some text
- Key-value pairs are separated by tabs or newlines
- Keys are separated from values by a colon
- Remaining whitespace surrounding keys and values needs to be stripped

So

>>> raw_table = '''\
... a: Ask\t y: Dividend Yield
... b: Bid\td: Dividend per Share
... b2: Ask (Realtime)\t r1: Dividend Pay Date
... b3: Bid (Realtime)\tq: Ex-Dividend Date
... p: Previous Close
... o: Open'''

I used \t as tabs, but literal tabs will work, too. The backslash in the 
first line is to avoid the empty first line. alternatively remove it and 
other leading/trailing whitespace with raw_table = raw_table.strip()

>>> pairs = [pair for line in raw_table.splitlines() for pair in 
line.split("\t")]
>>> pairs
['a: Ask', ' y: Dividend Yield', 'b: Bid', 'd: Dividend per Share', 'b2: Ask 
(Realtime)', ' r1: Dividend Pay Date', 'b3: Bid (Realtime)', 'q: Ex-Dividend 
Date', 'p: Previous Close', 'o: Open']
>>> pairs = [pair.partition(":")[::2] for pair in pairs]

pair.split(":") instead of partition()[::2] would work, too.

>>> pairs
[('a', ' Ask'), (' y', ' Dividend Yield'), ('b', ' Bid'), ('d', ' Dividend 
per Share'), ('b2', ' Ask (Realtime)'), (' r1', ' Dividend Pay Date'), 
('b3', ' Bid (Realtime)'), ('q', ' Ex-Dividend Date'), ('p', ' Previous 
Close'), ('o', ' Open')]
>>> d = {k.strip(): v.strip() for k, v in pairs}
>>> d
{'b2': 'Ask (Realtime)', 'q': 'Ex-Dividend Date', 'b3': 'Bid (Realtime)', 
'r1': 'Dividend Pay Date', 'd': 'Dividend per Share', 'y': 'Dividend Yield', 
'p': 'Previous Close', 'b': 'Bid', 'a': 'Ask', 'o': 'Open'}




More information about the Tutor mailing list