473,480 Members | 1,997 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

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 10525
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
3385
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
2367
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
2185
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
2967
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
1877
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
2387
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
43868
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
2554
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
5003
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...
0
7041
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
6908
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7081
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6737
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
6921
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
2995
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
2984
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1300
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
563
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.