simple question on dictionary usage
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sat Oct 27 10:07:23 EDT 2007
On Sat, 27 Oct 2007 04:29:51 +0000, Frank Stutzman wrote:
> My apologies in advance, I'm new to python
>
> Say, I have a dictionary that looks like this:
>
> record={'BAT': '14.4', 'USD': '24', 'DIF': '45', 'OAT': '16',
> 'FF': '3.9', 'C3': '343', 'E4': '1157', 'C1': '339', 'E6':
> '1182', 'RPM': '996', 'C6': '311', 'C5': '300', 'C4': '349',
> 'CLD': '0', 'E5': '1148', 'C2': '329', 'MAP': '15', 'OIL':
> '167', 'HP': '19', 'E1': '1137', 'MARK': '', 'E3': '1163',
> 'TIME': '15:43:54', 'E2': '1169'}
>
> From this dictionary I would like to create another dictionary calld
> 'egt') that has all of the keys that start with the letter 'E'. In
> otherwords it should look like this:
>
> egt = {'E6': '1182','E1': '1137','E4': '1157','E5': '1148',
> 'E2': '1169','E3': '1163'}
With my tongue firmly in cheek, I present the following obfuscated
solution:
eval("{" + reduce(lambda x,y: y+', '+x, [mo.group(1) for mo in __import__
('re').finditer(r"('E.*?'\s*:\s*'.*?'),?", str(record))], "") + "}")
The above should be a single line.
eval(), reduce(), lambda, string concatenation in the least efficient way
possible, regexes... could it get any worse than this?
--
Steven.
More information about the Python-list
mailing list