473,399 Members | 2,858 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,399 software developers and data experts.

container-indepentent iteration code ?


is there a way to iterate over the *values* in a list/dict/whatever,
regardless of whether it's a list, dict, or whatever? ie, the iteration
code will not know beforehand what kind of container it's getting.
Jul 18 '05 #1
7 1432
On Wed, 08 Sep 2004 19:27:38 -0400, flacco wrote:

is there a way to iterate over the *values* in a list/dict/whatever,
regardless of whether it's a list, dict, or whatever? ie, the iteration
code will not know beforehand what kind of container it's getting.


In what way does

for obj in container:

not meet your needs?

Jul 18 '05 #2
Jeremy Bowers wrote:
On Wed, 08 Sep 2004 19:27:38 -0400, flacco wrote:
is there a way to iterate over the *values* in a list/dict/whatever,
regardless of whether it's a list, dict, or whatever? ie, the iteration
code will not know beforehand what kind of container it's getting.


In what way does

for obj in container:

not meet your needs?


i always want obj to be the value. dicts, for example, yield keys
instead of values (i think?)...
Jul 18 '05 #3
On Wed, 08 Sep 2004 20:35:56 -0400, flacco wrote:
i always want obj to be the value. dicts, for example, yield keys
instead of values (i think?)...


Ah, that clarifies it for me. "Values" is a bit of an overloaded term. :-)

The problem you're running into here is that the "standard iterator" kind
of "defines" the "values" the container has. That's the only idea of
"default set of values in a container" that Python is going to understand.

Thus, since the fundamental issue is a disagreement between you and Python
about what constitutes a "value" out of a dict (and as the human in this
transaction you are the right one :-) ), I don't see any way to avoid
explaining your idea to Python. You can make it convenient:

def values(iterable):
if isinstance(iterable, dict):
return iterable.itervalues()
# Whatever other special cases you may need
return iter(iterable)

for obj in values(container):
# etc.

but there's no switch or anything that will do what you want. Sorry.
You're always going to have to explain what you mean by "whatever" to
Python.

Stepping up one meta-level, another possibility that you may consider is
creating some container classes that match whatever your heterogenous
containment needs are, then you can make *those* containers work naturally
without the function I showed above. Without knowing more about your
problem, I can't know if that is better in general.

Consider this:

class IterateGivesMeValues(dict):
# It is quite likely your domain will give you a better
# name :-)
def __iter__(self):
return self.itervalues()

igmv = IterateGivesMeValues()
igmv["key"] = "value"
for i in igmv:
print i

will print "value" instead of "dict". If you build your structures out of
such objects your life may, or may not, be easier.

Jul 18 '05 #4
[flacco]
is there a way to iterate over the *values* in a list/dict/whatever,
regardless of whether it's a list, dict, or whatever? ie, the iteration
code will not know beforehand what kind of container it's getting.


try:
it = obj.itervalues()
except AttributeError:
it = iter(obj)
for value in it:
. . .
Raymond Hettinger

Jul 18 '05 #5

"flacco" <fl*******@spambadTwilight-systems.com> wrote in message
news:10*************@corp.supernews.com...
Jeremy Bowers wrote:
On Wed, 08 Sep 2004 19:27:38 -0400, flacco wrote:
is there a way to iterate over the *values* in a list/dict/whatever,
regardless of whether it's a list, dict, or whatever? ie, the iteration
code will not know beforehand what kind of container it's getting.


In what way does

for obj in container:

not meet your needs?


i always want obj to be the value. dicts, for example, yield keys
instead of values (i think?)...


When iterators were introduced, there was discussion of whether

for x in somedict:

should iterate over dict.keys(), dict.values(), dict.items(), or continue
to be illegal. dict.keys() won as being most useful because most commonly
needed. Iterating over values or items continues to have to be explicit.

Terry J. Reedy

Jul 18 '05 #6
flacco <fl*******@spambadTwilight-systems.com> wrote:
...
In what way does

for obj in container:

not meet your needs?


i always want obj to be the value. dicts, for example, yield keys
instead of values (i think?)...


Yep, as Jeremy explained, iter(container) [[implicitly called by the for
statement]] lets the container decide which are the container's *items*.

If you don't like the way a container defines what its items are for
default iteration purposes you need to tweak things in the cases you
don't like (another example might be files: their items are lines --
what if you want characters, or blocks of 37 characters, or ...? no way
Python can possibly guess without explicit action on your part!).
Alex
Jul 18 '05 #7
def viter(container):
"""Iterate over values of a container"""
if hasattr(container, "itervalues"):
return container.itervalues()
return iter(container)

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)

iD8DBQFBQF6cJd01MZaTXX0RAgt3AJ9dHLhksoNnLnASjxYy6H WoQvzcQgCeIupe
ZH8D81nH8HYzqfh1x4iPlP0=
=oSx2
-----END PGP SIGNATURE-----

Jul 18 '05 #8

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

Similar topics

1
by: Wolfgang Lipp | last post by:
my question is: do we need container elements for repeating elements in data-centric xml documents? or is it for some reason very advisable to introduce containers in xml documents even where not...
2
by: Ney André de Mello Zunino | last post by:
Hello. The issue is quite known: you have a block-level container holding a set of floated elements and you need that the container's content height take the floated elements' dimensions into...
2
by: Maitre Bart | last post by:
What I want to perform is calling a member function of container 1 (CRunner), using as argument the value of a container 2 (CNames). The purpose is to transfer values from C2 into C1 using a...
19
by: Nafai | last post by:
Hi I want to write a function which erases al the repeated elements in a range. How should be the prototype? template <class Iterator> void eraseRepeated(Iterator begin, Iterator end); ...
3
by: jignesh shah | last post by:
Hi all, Is there a way to recover a single container if its been corrupted or mark bad without restoring whole tablespace? environment: db28.1/aix5.1/tsm/rs-6000. Regards Jignesh
9
by: horizon5 | last post by:
Hi, my collegues and I recently held a coding style review. All of the code we produced is used in house on a commerical project. One of the minor issues I raised was the common idiom of...
11
by: food4uk | last post by:
Dear all : I am not good at programming, please give a hand. My data structure is very similar as an array. I actually can use the std::vector as container to organize my data objects. However,...
2
by: Daniel Lipovetsky | last post by:
I would like for an object to "report" to a container object when a new instance is created or deleted. I could have a container object that is called when a new instance is created, as below. ...
1
by: Miked | last post by:
Hello: I'm relatively new to CSS, and I'm doing a site where I don't want to use any tables. I've gotten pretty far, and the site has the layout I want. My only problem is that I'm using the...
18
by: Goran | last post by:
Hi @ all! Again one small question due to my shakiness of what to use... What is better / smarter? private: vector<MyClass_t* itsVector; OR...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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...

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.