473,224 Members | 1,903 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Syntax for extracting multiple items from a dictionary

row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken", "state" :
"Alaska"}
cols = ("city", "state")

Is there a best-practices way to ask for an object containing only the keys
named in cols out of row? In other words, to get this:
{"city" : "Hoboken", "state" : "Alaska"}

Thanks,

shark
Jul 18 '05 #1
10 10505
shark wrote:
row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken", "state" :
"Alaska"}
cols = ("city", "state")

Is there a best-practices way to ask for an object containing only the keys
named in cols out of row? In other words, to get this:
{"city" : "Hoboken", "state" : "Alaska"}


Why would you need to do that? There's nothing you can do to the second
dictionary that you can't do to the first, so what's wrong with leaving
the extra items in place?
Jul 18 '05 #2
In article <Tu********************@rcn.net>, "shark" <no@spam.none>
wrote:
row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken", "state" :
"Alaska"}
cols = ("city", "state")

Is there a best-practices way to ask for an object containing only the keys
named in cols out of row? In other words, to get this:
{"city" : "Hoboken", "state" : "Alaska"}

Thanks,

shark


Just out of curiosity, why would you want to do that? Are you trying to
save on memory to store a lot of these things? If so, I suspect you'd
do even better (a few bytes per object) to store tuples of just the
values, i.e. ("Hoboken", "Alaska"), and unpack them as you need them.

But, to answer your question, I don't know of any standard way to do
what you want. It's easy enough to write (a production version would
probably want to catch KeyError's inside the for loop):

def getDictionarySlice (row, cols):
slice = {}
for key in cols:
slice[key] = row[key]
return slice

This won't work, but it would be kind of cool if it did:

def getOmnicientDictionarySlice (row, cols):
for key not in cols:
del row[key]

Hmmm. Maybe there's an April Fools PEP in there somewhere :-)
Actually, you could do:

def deleteUnwantedKeysInPlace (row, cols):
for key in row.keys():
if key not in cols:
del row[key]
Jul 18 '05 #3


shark schrieb:
row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken", "state" :
"Alaska"}
cols = ("city", "state")

Is there a best-practices way to ask for an object containing only the keys
named in cols out of row? In other words, to get this:
{"city" : "Hoboken", "state" : "Alaska"}


Untested:

dict( (key,value) for (key,value) in row.iteritems() if key in cols )

Works in Py2.4

Stefan
Jul 18 '05 #4
Stefan Behnel wrote:


shark schrieb:
row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken",
"state" :
"Alaska"}
cols = ("city", "state")

Is there a best-practices way to ask for an object containing only the
keys
named in cols out of row? In other words, to get this:
{"city" : "Hoboken", "state" : "Alaska"}

Untested:

dict( (key,value) for (key,value) in row.iteritems() if key in cols )

Works in Py2.4

Stefan


Or dict((key, row[key]) for key in cols).

regards,
anton.
Jul 18 '05 #5
On Tue, 30 Nov 2004 15:20:19 +0100, Stefan Behnel <be*******@gkec.informatik.tu-darmstadt.de> wrote:


shark schrieb:
row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken", "state" :
"Alaska"}
cols = ("city", "state")

Is there a best-practices way to ask for an object containing only the keys
named in cols out of row? In other words, to get this:
{"city" : "Hoboken", "state" : "Alaska"}
Untested:

dict( (key,value) for (key,value) in row.iteritems() if key in cols )


If there's an overall why for doing it at all, why not just iterate through
keys of interest? I.e., (untested)

dict( (key, row[key]) for key in cols )

Works in Py2.4

Stefan


Regards,
Bengt Richter
Jul 18 '05 #6
On Tue, 30 Nov 2004 21:54:46 GMT, bo**@oz.net (Bengt Richter) wrote:
[...]

If there's an overall why for doing it at all, why not just iterate through
keys of interest? I.e., (untested)

dict( (key, row[key]) for key in cols )

Sorry Anton, I didn't see your post. Newsfeed delays seem
to make this kind of duplication fairly likely ;-/

Regards,
Bengt Richter
Jul 18 '05 #7
"anton muhin" wrote:
Stefan Behnel wrote:


shark schrieb:
row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken",
"state" :
"Alaska"}
cols = ("city", "state")

Is there a best-practices way to ask for an object containing only the
keys
named in cols out of row? In other words, to get this:
{"city" : "Hoboken", "state" : "Alaska"}

Untested:

dict( (key,value) for (key,value) in row.iteritems() if key in cols )

Works in Py2.4

Stefan


Or dict((key, row[key]) for key in cols).

regards,
anton.


I'm on Py 2.3.3, and neither of these appear to work. Can someone confirm? I
can't see anything in the 2.4 release notes that point to where this would
have changed.

Thanks,

shark
Jul 18 '05 #8
On Wed, 1 Dec 2004 10:23:28 -0500, Dave Merrill <dm*******@usaq.netq> wrote:
"anton muhin" wrote:
Or dict((key, row[key]) for key in cols).


I'm on Py 2.3.3, and neither of these appear to work. Can someone confirm? I
can't see anything in the 2.4 release notes that point to where this would
have changed.


They use generator expressions, which were introduced by Python 2.4.
See <http://www.python.org/dev/doc/devel/whatsnew/node4.html>.

--
Cheers,
Simon B,
si***@brunningonline.net,
http://www.brunningonline.net/simon/blog/
Jul 18 '05 #9

The correct syntax is:

dict([(key, row[key]) for key in cols])

i.e. the list must be enclosed in [...].

/Jean Brouwers

In article <7O********************@rcn.net>, Dave Merrill
<dm*******@usaq.netq> wrote:
"anton muhin" wrote:
Stefan Behnel wrote:


shark schrieb:

> row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken",
> "state" :
> "Alaska"}
> cols = ("city", "state")
>
> Is there a best-practices way to ask for an object containing only the
> keys
> named in cols out of row? In other words, to get this:
> {"city" : "Hoboken", "state" : "Alaska"}
Untested:

dict( (key,value) for (key,value) in row.iteritems() if key in cols )

Works in Py2.4

Stefan


Or dict((key, row[key]) for key in cols).

regards,
anton.


I'm on Py 2.3.3, and neither of these appear to work. Can someone confirm? I
can't see anything in the 2.4 release notes that point to where this would
have changed.

Thanks,

shark

Jul 18 '05 #10
Dave Merrill wrote:
"anton muhin" wrote:
Or dict((key, row[key]) for key in cols).
I'm on Py 2.3.3, and neither of these appear to work.


You're probably getting the error shown. Try the change in
the line following it instead.

Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)]
row = {'fname': 'Frank', 'lname': 'Jones', 'city': 'Hoboken', 'state': 'Alaska'} cols = ['city', 'state']
dict((key, row[key]) for key in cols) File "<stdin>", line 1
dict((key, row[key]) for key in cols)
^
SyntaxError: invalid syntax dict([(key, row[key]) for key in cols])

{'city': 'Hoboken', 'state': 'Alaska'}

I can't see anything in the 2.4 release notes that point to where this would
have changed.


See http://www.python.org/2.4/highlights.html and search for
"generator expressions".

-Peter
Jul 18 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

22
by: Tuang | last post by:
I'm checking out Python as a candidate for replacing Perl as my "Swiss Army knife" tool. The longer I can remember the syntax for performing a task, the more likely I am to use it on the spot if...
16
by: Daniel Klein | last post by:
Hello, I'm quite new to Python, and since a not-so-superficial look into the docs didn't answer my question (although it still feels quite basic), I decided to turn to this place: Is there a...
1
by: garett | last post by:
Hello, I have been reading text processing in python and in the appendix the author describes: >>> sides = >>> zip(*zip(*sides)) what is this asterisk-list syntax called? Any suggestions for...
2
by: Steve | last post by:
Hi, I have a very long string, someting like: DISPLAY=localhost:0.0,FORT_BUFFERED=true, F_ERROPT1=271\,271\,2\,1\,2\,2\,2\,2,G03BASIS=/opt/g03b05/g03/basis,...
12
by: Donnal Walter | last post by:
The following method is defined in one of my classes: def setup(self, items={}): """perform setup based on a dictionary of items""" if 'something' in items: value = items # now do something...
31
by: Brian Sabbey | last post by:
Here is a pre-PEP for what I call "suite-based keyword arguments". The mechanism described here is intended to act as a complement to thunks. Please let me know what you think. Suite-Based...
17
by: Roland Hall | last post by:
Is there a way to return multiple values from a function without using an array? Would a dictionary object work better? -- Roland Hall /* This information is distributed in the hope that it...
20
by: W Karas | last post by:
Would the fear factor for concepts be slightly reduced if, instead of: concept C<typename T> { typename T::S; int T::mem(); int nonmem(); };
2
by: englishman69 | last post by:
Hello, I have been banging my head against this one for a while... Searches online have revealed many different proposals for correcting my issue but none that I can follow! My basic situation...
1
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
0
by: veera ravala | last post by:
ServiceNow is a powerful cloud-based platform that offers a wide range of services to help organizations manage their workflows, operations, and IT services more efficiently. At its core, ServiceNow...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: mar23 | last post by:
Here's the situation. I have a form called frmDiceInventory with subform called subfrmDice. The subform's control source is linked to a query called qryDiceInventory. I've been trying to pick up the...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...

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.