Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 843205
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T06:05:16+00:00 2026-05-15T06:05:16+00:00

In a Python program I’m writing I’ve compared using a for loop and increment

  • 0

In a Python program I’m writing I’ve compared using a for loop and increment variables versus list comprehension with map(itemgetter) and len() when counting entries in dictionaries which are in a list. It takes the same time using a each method. Am I doing something wrong or is there a better approach?

Here is a greatly simplified and shortened data structure:

list = [
  {'key1': True, 'dontcare': False, 'ignoreme': False, 'key2': True, 'filenotfound': 'biscuits and gravy'},
  {'key1': False, 'dontcare': False, 'ignoreme': False, 'key2': True, 'filenotfound': 'peaches and cream'},
  {'key1': True, 'dontcare': False, 'ignoreme': False, 'key2': False, 'filenotfound': 'Abbott and Costello'},
  {'key1': False, 'dontcare': False, 'ignoreme': True, 'key2': False, 'filenotfound': 'over and under'},
  {'key1': True, 'dontcare': True, 'ignoreme': False, 'key2': True, 'filenotfound': 'Scotch and... well... neat, thanks'}
]

Here is the for loop version:

#!/usr/bin/env python
# Python 2.6
# count the entries where key1 is True
# keep a separate count for the subset that also have key2 True

key1 = key2 = 0
for dictionary in list:
    if dictionary["key1"]:
        key1 += 1
        if dictionary["key2"]:
            key2 += 1
print "Counts: key1: " + str(key1) + ", subset key2: " + str(key2)

Output for the data above:

Counts: key1: 3, subset key2: 2

Here is the other, perhaps more Pythonic, version:

#!/usr/bin/env python
# Python 2.6
# count the entries where key1 is True
# keep a separate count for the subset that also have key2 True
from operator import itemgetter
KEY1 = 0
KEY2 = 1
getentries = itemgetter("key1", "key2")
entries = map(getentries, list)
key1 = len([x for x in entries if x[KEY1]])
key2 = len([x for x in entries if x[KEY1] and x[KEY2]])
print "Counts: key1: " + str(key1) + ", subset key2: " + str(key2)

Output for the data above (same as before):

Counts: key1: 3, subset key2: 2

I’m a tiny bit surprised these take the same amount of time. I wonder if there’s something faster. I’m sure I’m overlooking something simple.

One alternative I’ve considered is loading the data into a database and doing SQL queries, but the data doesn’t need to persist and I’d have to profile the overhead of the data transfer, etc., and a database may not always be available.

I have no control over the original form of the data.

The code above is not going for style points.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T06:05:17+00:00Added an answer on May 15, 2026 at 6:05 am

    I think you’re measuring incorrectly by swamping the code to be measured in a lot of overhead (running at top module level instead of in a function, doing output). Putting the two snippets into functions named forloop and withmap, and adding a * 100 to the list’s definition (after the closing ]) to make the measurement a little substantial, I see, on my slow laptop:

    $ py26 -mtimeit -s'import co' 'co.forloop()'
    10000 loops, best of 3: 202 usec per loop
    $ py26 -mtimeit -s'import co' 'co.withmap()'
    10 loops, best of 3: 601 usec per loop
    

    i.e., the allegedly “more pythonic” approach with map is three times slower than the plain for approach — which tells you that it’s not really “more pythonic”;-).

    The mark of good Python is simplicity, which, to me, recommends what I hubris-ly named…:

    def thebest():
      entries = [d['key2'] for d in list if d['key1']]
      return len(entries), sum(entries)
    

    which, on measurement, saves between 10% and 20% time over the forloop approach.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am writing a python program for google appengine using jinja2 as my template
I'm writing python program to build mac-address cache using pcap. But pcap module for
For the python program I am writing I would like to give the opportunity
I'm writing a python program that uses scons to build an .exe and then
The Python program I'm writing needs to start a local PHP script outside of
I'm writing a python program that will spawn a subprocess to basically clone a
I'm writing an python program (gui in gtk) (linux btw.) I want to have
My python program (Python 2.6) works fine when I run it using the Python
A Python program I'm writing is to read a set number of lines from
I'm writing a Python program with a GUI built with the Tkinter module. I'm

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.