473,386 Members | 1,791 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,386 software developers and data experts.

dict.items() vs dict.iteritems and similar questions

When is it appropriate to use dict.items() vs dict.iteritems. Both
seem to work for something like:

for key,val in mydict.items():
print key,val

for key,val in mydict.iteritems():
print key,val

Also, when is it appropriate to use range() vs xrange(). From my
understanding, xrange() essentially gives you an iterator across a
range, so it should be used when iterating. Should you only use
range() when want to physically store the range as a list?

Thanks,
Drew

Mar 14 '07 #1
19 37238
Drew a écrit :
When is it appropriate to use dict.items() vs dict.iteritems. Both
seem to work for something like:

for key,val in mydict.items():
print key,val

for key,val in mydict.iteritems():
print key,val

Also, when is it appropriate to use range() vs xrange(). From my
understanding, xrange() essentially gives you an iterator across a
range, so it should be used when iterating. Should you only use
range() when want to physically store the range as a list?
iteritems and xrange only provide values when requested.
items and range build complete list when called.

Both work, you may prefer xrange/iteritems for iteration on large
collections, you may prefer range/items when processing of the result
value explicitly need a list (ex. calculate its length) or when you are
going to manipulate the original container in the loop.

A+

Laurent.
Mar 14 '07 #2
On Mar 14, 11:44 am, Laurent Pointal <laurent.poin...@limsi.frwrote:
Both work, you may prefer xrange/iteritems for iteration on large
collections, you may prefer range/items when processing of the result
value explicitly need a list (ex. calculate its length) or when you are
going to manipulate the original container in the loop.

A+

Laurent.
Laurent -

Extremely helpful, exactly what I was looking for.

Thanks,
Drew

Mar 14 '07 #3
# Just by looking at the output, it seems pretty obvious that xrange
would be more memory effcient for large ranges:

print "With range():",range(100,200)
print
print "With xrange():",xrange(100,200)

d = {1:2,2:3,3:4}
d.items()
d.iteritems()

# I have been curious to use Pysizer (which requires patching Python)
to demonstrate the difference.

Drew wrote:
When is it appropriate to use dict.items() vs dict.iteritems. Both
seem to work for something like:

for key,val in mydict.items():
print key,val

for key,val in mydict.iteritems():
print key,val

Also, when is it appropriate to use range() vs xrange(). From my
understanding, xrange() essentially gives you an iterator across a
range, so it should be used when iterating. Should you only use
range() when want to physically store the range as a list?

Thanks,
Drew

--
Shane Geiger
IT Director
National Council on Economic Education
sg*****@ncee.net | 402-438-8958 | http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy
Mar 14 '07 #4
Laurent Pointal wrote:
Both work, you may prefer xrange/iteritems for iteration on large
collections, you may prefer range/items when processing of the result
value explicitly need a list (ex. calculate its length) or when you are
going to manipulate the original container in the loop.
xrange actually supports len():
>>len(xrange(10))
10
Mar 14 '07 #5
>When is it appropriate to use dict.items() vs dict.iteritems.

LaurentBoth work, you may prefer xrange/iteritems for iteration on
Laurentlarge collections...

I find "iter<anything>" to be extremely ugly and hope to avoid using them
altogether until they are gone in Py3k.

Skip
Mar 14 '07 #6
On Mar 14, 2:53 pm, s...@pobox.com wrote:
>When is it appropriate to use dict.items() vs dict.iteritems.

LaurentBoth work, you may prefer xrange/iteritems for iteration on
Laurentlarge collections...

I find "iter<anything>" to be extremely ugly and hope to avoid using them
altogether until they are gone in Py3k.

Skip
Skip -

Ugly, maybe, but don't you take a decent performance hit when loading
the entire dict into memory at once? Especially if the dict is large?

Mar 14 '07 #7
>I find "iter<anything>" to be extremely ugly and hope to avoid using
>them altogether until they are gone in Py3k.
DrewUgly, maybe, but don't you take a decent performance hit when
Drewloading the entire dict into memory at once? Especially if the
Drewdict is large?

Sure, but I try hard to keep my dicts small. ;-)

Skip
Mar 14 '07 #8
Laurent Pointal <la*************@limsi.frwrites:
Both work, you may prefer xrange/iteritems for iteration on large
collections, you may prefer range/items when processing of the result
value explicitly need a list (ex. calculate its length) or when you are
going to manipulate the original container in the loop.
You can use len(d) if d is a dict.
Mar 14 '07 #9
Paul Rubin a écrit :
Laurent Pointal <la*************@limsi.frwrites:
>Both work, you may prefer xrange/iteritems for iteration on large
collections, you may prefer range/items when processing of the result
value explicitly need a list (ex. calculate its length) or when you are
going to manipulate the original container in the loop.

You can use len(d) if d is a dict.
Yes, as long as you have a semantic relation between the original dict
and the extracted keys. But once you have extracted the keys, and pass
them around your functions, if you miss the relationship, you have
either a list container or a generator. Not considering the case where
original dict is modified between keys extraction and keys usage...

But as we dont know more about OP needs...
A+

Laurent.
Mar 15 '07 #10
Laurent Pointal:
you may prefer range/items when processing of the result
value explicitly need a list (ex. calculate its length)
Creating a very long list just to know the len of an iterator is
barbaric, so sometimes I use this:

def leniter(iterator):
if hasattr(iterator, "__len__"):
return len(iterator)
nelements = 0
for _ in iterator:
nelements += 1
return nelements

Bye,
bearophile

Mar 15 '07 #11
be************@lycos.com wrote:
Laurent Pointal:
>you may prefer range/items when processing of the result
value explicitly need a list (ex. calculate its length)

Creating a very long list just to know the len of an iterator is
barbaric, so sometimes I use this:

def leniter(iterator):
if hasattr(iterator, "__len__"):
return len(iterator)
nelements = 0
for _ in iterator:
nelements += 1
return nelements
Of course this is a little like the Heisenberg uncertainty principle if
the iterator has no __len__ attribute - once you know how long it is you
no longer have access to the elements. Or did I miss something?

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note: http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

Mar 15 '07 #12
Steve Holden a écrit :
be************@lycos.com wrote:
>Laurent Pointal:
>>you may prefer range/items when processing of the result
value explicitly need a list (ex. calculate its length)

Creating a very long list just to know the len of an iterator is
barbaric, so sometimes I use this:

def leniter(iterator):
if hasattr(iterator, "__len__"):
return len(iterator)
nelements = 0
for _ in iterator:
nelements += 1
return nelements
Of course this is a little like the Heisenberg uncertainty principle if
the iterator has no __len__ attribute - once you know how long it is you
no longer have access to the elements. Or did I miss something?
yes, that's one of the side effects. Another interesting case:

import itertools
it = itertools.cycle(range(10))
print "it has %d elements" % leniter(it)
Mar 15 '07 #13
Steve Holden:
once you know how long it is you
no longer have access to the elements. Or did I miss something?
Now and then I need to know how many elements there are, and not what
they are, so in those situations storing them isn't necessary.

Bye,
bearophile

Mar 15 '07 #14
Steve Holden <st***@holdenweb.comwrote:
be************@lycos.com wrote:
Laurent Pointal:
you may prefer range/items when processing of the result
value explicitly need a list (ex. calculate its length)
Creating a very long list just to know the len of an iterator is
barbaric, so sometimes I use this:

def leniter(iterator):
if hasattr(iterator, "__len__"):
return len(iterator)
nelements = 0
for _ in iterator:
nelements += 1
return nelements
Of course this is a little like the Heisenberg uncertainty principle if
the iterator has no __len__ attribute - once you know how long it is you
no longer have access to the elements. Or did I miss something?
Right. However, "return sum(1 for _ in iterator)" may be a handier way
to express the same desctructive semantics as the last 4 lines here.
Alex
Mar 15 '07 #15
al***@mac.com (Alex Martelli) wrote:
>Of course this is a little like the Heisenberg uncertainty principle if
the iterator has no __len__ attribute - once you know how long it is you
no longer have access to the elements. Or did I miss something?

Right. However, "return sum(1 for _ in iterator)" may be a handier way
to express the same desctructive semantics as the last 4 lines here.
I think I'd prefer the barbaric:

return len(list(iterator))

since at least it is guaranteed to terminate.
Mar 15 '07 #16

DuncanI think I'd prefer the barbaric:

Duncan return len(list(iterator))

Duncansince at least it is guaranteed to terminate.

Are you sure? There's no guarantee that an iterator will terminate:

len(list(itertools.cycle(range(10))))

Skip
Mar 15 '07 #17
In <ma***************************************@python. org>, skip wrote:
Are you sure? There's no guarantee that an iterator will terminate:

len(list(itertools.cycle(range(10))))
You have infinite memory? ;-)

Ciao,
Marc 'BlackJack' Rintsch

Mar 15 '07 #18
Alex Martelli:
Right. However, "return sum(1 for _ in iterator)" may be a handier way
to express the same desctructive semantics as the last 4 lines here.
With the speed tests I have done my version did come out as the faster
one.

Bye,
bearophile

Mar 15 '07 #19
Marc 'BlackJack' Rintsch <bj****@gmx.netwrote:
In <ma***************************************@python. org>, skip wrote:
>Are you sure? There's no guarantee that an iterator will terminate:

len(list(itertools.cycle(range(10))))

You have infinite memory? ;-)
Strangely, Skip's example is exactly the one I tested before posting my
claim that it would terminate.
Mar 15 '07 #20

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

Similar topics

6
by: Tertius | last post by:
Is there a method to create a dict from a list of keys and a list of values ? TIA Tertius
15
by: Irmen de Jong | last post by:
Hi I have this dict that maps a name to a sequence of other names. I want to have it reversed, i.e., map the other names each to the key they belong to (yes, the other names are unique and they...
2
by: kevin parks | last post by:
hi. I've been banging my head against this one a while and have asked around, and i am throwing this one out there in the hopes that some one can shed some light on what has turned out to be a...
8
by: bearophileHUGS | last post by:
I'm frequently using Py2.4 sets, I find them quite useful, and I like them, even if they seem a little slower than dicts. Sets also need the same memory of dicts (can they be made to use less...
7
by: Marcio Rosa da Silva | last post by:
Hi! In dictionaries, unlinke lists, it doesn't matter the order one inserts the contents, elements are stored using its own rules. Ex: >>> d = {3: 4, 1: 2} >>> d {1: 2, 3: 4}
15
by: George Sakkis | last post by:
Although I consider dict(**kwds) as one of the few unfortunate design choices in python since it prevents the future addition of useful keyword arguments (e.g a default value or an orderby...
8
by: Brian L. Troutwine | last post by:
I've got a problem that I can't seem to get my head around and hoped somebody might help me out a bit: I've got a dictionary, A, that is arbitarily large and may contains ints, None and more...
1
by: bearophileHUGS | last post by:
The PEP 3100: http://www.python.org/dev/peps/pep-3100/ says: Return iterators instead of lists where appropriate for atomic type methods (e.g. dict.keys(), dict.values(), dict.items(), etc.);...
2
by: Noah | last post by:
What is the fastest way to select N items at a time from a dictionary? I'm iterating over a dictionary of many thousands of items. I want to operate on only 100 items at a time. I want to avoid...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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
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...

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.