simple question on dictionary usage

F

Frank Stutzman

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.

Thanks in advance
 
E

Edward Kozlowski

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.

Thanks in advance

I think this should do the trick. There's probably something more
concise than this, but I can't think of it at the moment.

egt = {}
for key in record:
if key.startswith('E'):
egt[key] = record[key]

print egt
{'E5': '1148', 'E4': '1157', 'E6': '1182', 'E1': '1137', 'E3': '1163',
'E2': '1169'}


-Edward Kozlowski
 
K

Karthik Gurusamy

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):
.... '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 in record if k.startswith('E')])
egt
{'E5': '1148', 'E4': '1157', 'E6': '1182', 'E1': '1137', 'E3': '1163',
'E2': '1169'}

Karthik
 
R

Ryan Ginstrom

On Behalf Of Edward Kozlowski
I think this should do the trick. There's probably something
more concise than this, but I can't think of it at the moment.

egt = {}
for key in record:
if key.startswith('E'):
egt[key] = record[key]

Not much more concise, but another way:

egt = dict((key, record[key])
for key in record
if key.startswith('E'))

Regards,
Ryan Ginstrom
 
F

Frank Millman

Frank said:
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 work -

egt = dict([i for i in d.items() if i[0].startswith('E')])

Frank Millman
 
F

Frank Millman

This should work -
egt = dict([i for i in d.items() if i[0].startswith('E')])

Of course I meant record.items(), not d.items(). Sorry.

Frank

On reflection, although my solution is a bit shorter than some others,
it may not be as efficient, as it retrieves the key and value for
*every* entry in 'record' before testing whether the key begins with
'E'.

If the dictionary is large, this may be a consideration.

Frank
 
D

Dustan

This should work -
egt = dict([i for i in d.items() if i[0].startswith('E')])
Of course I meant record.items(), not d.items(). Sorry.

On reflection, although my solution is a bit shorter than some others,
it may not be as efficient, as it retrieves the key and value for
*every* entry in 'record' before testing whether the key begins with
'E'.

That can be fixed by using record.iteritems() instead of
record.items().
 
B

Bruno Desthuilliers

Frank Stutzman a écrit :
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,

Indeed !-)
but somehow with all my googling I've
not found a hint.

egt = dict((k, v) for k, v in record.iteritems() if k.startswith('E'))
 
B

bearophileHUGS

My take too :)

dict(item for item in record.iteritems() if item[0][0] == 'E')

Bye,
bearophile
 
M

Marc 'BlackJack' Rintsch

My take too :)

dict(item for item in record.iteritems() if item[0][0] == 'E')

``s.startswith('E')`` is a little safer than ``s[0] == 'E'`` as the former
returns `False` if `s` is empty while the latter raises an `IndexError`.

Ciao,
Marc 'BlackJack' Rintsch
 
S

Steven D'Aprano

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?
 
F

Frank Stutzman

Wow, what a great group! Lots of useful and kind suggestions to what I was
sure was a fairly dumb question. A few comments on some selected suggestions
(but I appreciate all of them)

Edward said:
egt = {}
for key in record:
if key.startswith('E'):
egt[key] = record[key]

I actually had come up with something like this, but thought it wasn't
quite as pythonish as it should be. It is certainly much more readable
to a neophyte to python.

Bruno said:
egt = dict((k, v) for k, v in record.iteritems() if k.startswith('E'))

This is what I was looking for. I thought I had seen something simular
to this in one of the tutorials I had read, but couldn't seem to find it.

Steven D'Aprano:
eval("{" + reduce(lambda x,y: y+', '+x, [mo.group(1) for mo in __import__
('re').finditer(r"('E.*?'\s*:\s*'.*?'),?", str(record))], "") + "}")

Ah! Now this is one solution I can get my teeth into. If its not obvious,
I'm a recovering perl programmer.

Thanks to all
 
B

bearophileHUGS

Marc 'BlackJack' Rintsch>``s.startswith('E')`` is a little safer than
``s[0] == 'E'`` as the former returns `False` if `s` is empty while
the latter raises an `IndexError`.<

Thank you.
In this problem if there is an empty key in the record dict then maybe
it's better to raise an IndexError, because probably that's not a
normal condition. Sometimes less safe is more safe :)

With few tests I have seen that (using Psyco) this is probably the
faster solution (and it's quite readable by a newbe too):

record2 = {}
for k in record:
if k[0] == 'E':
record2[k] = record[k]

Misteriously with Psyco it becomes faster than even the equivalent D
language solution (keys starting with "E" are about 5% of the total)
that is statically typed and generally very fast:

string[string] record2;
foreach(k, v; record)
if (k[0] == 'E')
record2[k] = v;

Bye,
bearophile
 
?

=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=

egt = {}
for key in record:
if key.startswith('E'):
egt[key] = record[key]

I actually had come up with something like this, but thought it wasn't
quite as pythonish as it should be. It is certainly much more readable
to a neophyte to python.

My recommendation: forget about the comprehension-based ones. It *is*
Pythonic to have the code readable to a neophyte; there is no price to
win for shortness or cuteness.
This is what I was looking for. I thought I had seen something simular
to this in one of the tutorials I had read, but couldn't seem to find it.

And you consider this readable? I find it way too complex.
Ah! Now this is one solution I can get my teeth into. If its not obvious,
I'm a recovering perl programmer.

Ok, I now see why you can appreciate the comprehension-based one :)

Again, much of Python's strength comes from it being readable. Simple
is better than complex, and sparse is better than dense, and readability
counts (import this).

Regards,
Martin
 
B

Bruno Desthuilliers

Martin v. Löwis a écrit :
egt = {}
for key in record:
if key.startswith('E'):
egt[key] = record[key]

I actually had come up with something like this, but thought it wasn't
quite as pythonish as it should be. It is certainly much more readable
to a neophyte to python.


My recommendation: forget about the comprehension-based ones. It *is*
Pythonic to have the code readable to a neophyte; there is no price to
win for shortness or cuteness.

While I wholefully agree that readability is not something to
undervalue, I would not bash out list-comps (or generator-expressions,
as is the case below) based solutions for such a simple use-case.
Readability is not dumbness neither, and even if list-comps/generator
expression may be something new for most Python newbies, they *are* by
now the canonical, idiomatic Python way in this situation.
And you consider this readable? I find it way too complex.

As far as I'm concerned, I do find this solution much more readable than
it's more imperative counterpart.
 
B

Bruno Desthuilliers

Steven D'Aprano a écrit :
(snip)
eval("{" + reduce(lambda x,y: y+', '+x, [mo.group(1) for mo in __import__
('re').finditer(r"('E.*?'\s*:\s*'.*?'),?", str(record))], "") + "}")

Maman !

Steven, you choose the wrong language. You definitively want Perl !
 
R

r.grimm

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):

... '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')])
{'E5': '1148', 'E4': '1157', 'E6': '1182', 'E1': '1137', 'E3': '1163',
'E2': '1169'}

Karthik


Thanks in advance

Hallo,
a functional and concise way.

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

Rainer
 
B

Bruno Desthuilliers

(e-mail address removed) a écrit :
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')])

{'E5': '1148', 'E4': '1157', 'E6': '1182', 'E1': '1137', 'E3': '1163',
'E2': '1169'}

Karthik



Thanks in advance


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).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,147
Latest member
CarenSchni
Top