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

accessing keys in dict

hi,

a_dict = {'name':'apple', 'color':'red', 'texture':'smooth',
'shape':'sphere'}

is there any difference between ..

for key in a_dict:

from

for key in a_dict.keys():
which is more preferred? any difference in performance?

THanks
james

Aug 15 '07 #1
3 5110
In message <11**********************@l22g2000prc.googlegroups .com>,
james_027 wrote:
is there any difference between ..

for key in a_dict:

from

for key in a_dict.keys():
I'm assuming the former is equivalent to

for key in a_dict.iterkeys() :
Aug 25 '07 #2
On Aug 25, 7:41 am, Lawrence D'Oliveiro <l...@geek-
central.gen.new_zealandwrote:
In message <1187143106.021325.104...@l22g2000prc.googlegroups .com>,

james_027 wrote:
is there any difference between ..
for key in a_dict:
from
for key in a_dict.keys():

I'm assuming the former is equivalent to

for key in a_dict.iterkeys() :
Never assume. A better approach would be to experiment:

>>a_dict = {'name':'apple', 'color':'red', 'texture':'smooth',
'shape':'sphere'}
>>for i in a_dict: print i
color
shape
name
texture
>>for i in a_dict.iterkeys(): print i
color
shape
name
texture
>>for i in a_dict.itervalues(): print i
red
sphere
apple
smooth
>>for i in a_dict.iteritems(): print i
('color', 'red')
('shape', 'sphere')
('name', 'apple')
('texture', 'smooth')

Aug 25 '07 #3
On Sat, 25 Aug 2007 19:05:07 +0000, Dustan wrote:
Never assume. A better approach would be to experiment:
I assume that you would not like it if I poked you in the eye with a
sharp stick, but perhaps I better experiment...

*wink*

More seriously, if you wish to compare dict.keys() and dict.iterkeys(),
iterating over them doesn't help you because it shows only the
similarities, not the differences. But this will:
>>d = {1:"one", 2:"two"}
d.keys()
[1, 2]
>>d.iterkeys()
<dictionary-keyiterator object at 0xb7ecd280>

dict.keys() retrieves all the keys at once, up front, whether you need
them all or not. dict.iterkeys() returns an iterator which retrieves the
keys lazily, only when needed. Iterating over the dict itself is the same
as using iterkeys:
>>iter(d)
<dictionary-keyiterator object at 0xb7ecd4a0>
Performance-wise, the difference for small dicts may be trivial:
>>d = dict(zip(xrange(1000), xrange(1000)))
import timeit
timeit.Timer("for key in d: pass", "from __main__ import d").repeat()
[71.805022954940796, 71.10006308555603, 70.985043048858643]
>>timeit.Timer("for key in d.keys(): pass",
.... "from __main__ import d").repeat()
[80.323757886886597, 76.463414907455444, 76.681307792663574]

A six second difference on a million iterations of the loop is probably
not worth losing sleep over. But if your dict is very big, things may be
different:
>>d = dict(zip(xrange(1000000), xrange(1000000)))
timeit.Timer("for key in d: pass",
.... "from __main__ import d").repeat(number=100) # I don't have all day...
[9.2374939918518066, 8.3636147975921631, 8.3667001724243164]
>>timeit.Timer("for key in d.keys(): pass",
.... "from __main__ import d").repeat(number=100)
[13.776750087738037, 12.756224155426025, 12.697851181030273]

A four second difference on a hundred iterations of the loop _is_
something worth worrying about. Fortunately, Python makes it no worry at
all: just iterate on the dict regardless of whether your dict is small or
large, and you won't go wrong.
--
Steven.
Aug 26 '07 #4

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

Similar topics

8
by: Steven Bethard | last post by:
Sorry if this is a repost -- it didn't appear for me the first time. So I was looking at the Language Reference's discussion about emulating container types, and nowhere in it does it mention...
57
by: Egor Bolonev | last post by:
why functions created with lambda forms cannot contain statements? how to get unnamed function with statements?
90
by: Christoph Zwerschke | last post by:
Ok, the answer is easy: For historical reasons - built-in sets exist only since Python 2.4. Anyway, I was thinking about whether it would be possible and desirable to change the old behavior in...
14
by: vatamane | last post by:
This has been bothering me for a while. Just want to find out if it just me or perhaps others have thought of this too: Why shouldn't the keyset of a dictionary be represented as a set instead of a...
24
by: kdotsky | last post by:
Hello, I am using some very large dictionaries with keys that are long strings (urls). For a large dictionary these keys start to take up a significant amount of memory. I do not need access to...
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.);...
13
by: Nader | last post by:
Hello, I have a dictionary and will get all keys which have the same values. d = {('a' : 1), ('b' : 3), ('c' : 2),('d' : 3),('e' : 1),('f' : 4)} I will something as : d.keys(where their...
10
by: ++imanshu | last post by:
Hi, Wouldn't it be nicer to have 'in' return values (or keys) for both arrays and dictionaries. Arrays and Dictionaries looked so similar in Python until I learned this difference. Thanks,...
12
by: Florian Brucker | last post by:
Hi everybody! Given a dictionary, I want to create a clustered version of it, collecting keys that have the same value: {1:, 2:, 3:} That is, generate a new dict which holds for each value...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
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: 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
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
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...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

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.