471,350 Members | 1,631 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,350 software developers and data experts.

simple question on dictionary usage



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
--
Frank Stutzman
Oct 27 '07 #1
19 1232
On Oct 26, 11:29 pm, Frank Stutzman <stutz...@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.

Thanks in advance

--
Frank Stutzman
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

Oct 27 '07 #2
On Oct 26, 9:29 pm, Frank Stutzman <stutz...@skywagon.kjsl.comwrote:
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 in record if k.startswith('E')])
egt
{'E5': '1148', 'E4': '1157', 'E6': '1182', 'E1': '1137', 'E3': '1163',
'E2': '1169'}

Karthik
>
Thanks in advance

--
Frank Stutzman

Oct 27 '07 #3
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

Oct 27 '07 #4

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'}
This should work -

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

Frank Millman

Oct 27 '07 #5
>
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

Oct 27 '07 #6
On Oct 27, 8:02 am, Frank Millman <fr...@chagford.comwrote:
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

Oct 27 '07 #7
On Oct 27, 1:16 am, Frank Millman <fr...@chagford.comwrote:
On Oct 27, 8:02 am, Frank Millman <fr...@chagford.comwrote:
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'.
That can be fixed by using record.iteritems() instead of
record.items().
If the dictionary is large, this may be a consideration.

Frank

Oct 27 '07 #8
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'))
Oct 27 '07 #9
My take too :-)

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

Bye,
bearophile

Oct 27 '07 #10
On Sat, 27 Oct 2007 05:23:30 -0700, bearophileHUGS wrote:
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
Oct 27 '07 #11
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.
Oct 27 '07 #12
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 Kozlowski wrote:
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 Desthuilliers wrote:
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
--
Frank Stutzman

Oct 27 '07 #13
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

Oct 28 '07 #14
>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.
>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.
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
Oct 28 '07 #15
On Oct 27, 8:58 am, Marc 'BlackJack' Rintsch <bj_...@gmx.netwrote:
On Sat, 27 Oct 2007 05:23:30 -0700, bearophileHUGS wrote:
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`.
A string slice is safe and faster though: if s[:1] == 'E'.

George

Oct 29 '07 #16
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.
>
>>>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.


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.
Oct 29 '07 #17
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 !
Oct 29 '07 #18
On Oct 27, 6:42 am, Karthik Gurusamy <kar1...@gmail.comwrote:
On Oct 26, 9:29 pm, Frank Stutzman <stutz...@skywagon.kjsl.comwrote:
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 way.

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

Rainer

Nov 3 '07 #19
r.*****@science-computing.de a écrit :
On Oct 27, 6:42 am, Karthik Gurusamy <kar1...@gmail.comwrote:
>>On Oct 26, 9:29 pm, Frank Stutzman <stutz...@skywagon.kjsl.comwrote:

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

Nov 4 '07 #20

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

125 posts views Thread by Raymond Hettinger | last post: by
90 posts views Thread by Christoph Zwerschke | last post: by
8 posts views Thread by Brian P | last post: by
18 posts views Thread by Rune B | last post: by
4 posts views Thread by NullQwerty | last post: by
4 posts views Thread by =?utf-8?B?TWFjaWVqIEJsaXppxYRza2k=?= | last post: by
11 posts views Thread by not_a_commie | last post: by
20 posts views Thread by Simon Strobl | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.