simple question on dictionary usage

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sun Nov 4 16:56:22 EST 2007


r.grimm at science-computing.de a écrit :
> On Oct 27, 6:42 am, Karthik Gurusamy <kar1... at gmail.com> wrote:
> 
>>On Oct 26, 9:29 pm, Frank Stutzman <stutz... at skywagon.kjsl.com> 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'}
>>
>>>This should be pretty easy, but somehow with all my googling I've
>>>not found a hint.
>>
>>One possible solution (read list-comprehension if you not familiar
>>with it):
>>
>>
>>>>>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'}>>> egt =dict([(k,record[k]) for k inrecordif k.startswith('E')])
>>
>>>>>egt
>>
>>{'E5': '1148', 'E4': '1157', 'E6': '1182', 'E1': '1137', 'E3': '1163',
>>'E2': '1169'}
>>
>>Karthik
>>
>>
>>
>>
>>>Thanks in advance
>>
>>>--
>>>Frank Stutzman
> 
> 
> Hallo,
> a functional and concise

and not necessarily efficient

> way.
> 
> egt= dict( filter( lambda item: item[0][0] == "E" ,
> record.iteritems() ))

List comprehensions and generator expressions are just as 'functional' 
as lambdas (list comps comes from Haskell FWIW).




More information about the Python-list mailing list