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

Accumulating values in dictionary

Given a bunch of objects that all have a certain property, I'd like to
accumulate the totals of how many of the objects property is a certain
value. Here's a more intelligible example:

Users all have one favorite food. Let's create a dictionary of
favorite foods as the keys and how many people have that food as their
favorite as the value.

d = {}
for person in People:
fav_food = person.fav_food
if d.has_key(fav_food):
d[fav_food] = d[fav_food] + 1
else:
d[fav_food] = 1

d ends up being something like: {'pie': 400, 'pizza': 200, 'burgers':
100} if 400 people like pie, 200 like pizza and 100 like burgers.

There's nothing wrong (that I know of) by doing it as I have up there,
but is there a simpler, easier way? Looking forward to hearing about
how much of a n00b I am. Thanks in advance!
Jun 27 '08 #1
3 6247
On May 20, 12:26 pm, Zack <zhalbre...@gmail.comwrote:
Given a bunch of objects that all have a certain property, I'd like to
accumulate the totals of how many of the objects property is a certain
value. Here's a more intelligible example:

Users all have one favorite food. Let's create a dictionary of
favorite foods as the keys and how many people have that food as their
favorite as the value.

d = {}
for person in People:
fav_food = person.fav_food
if d.has_key(fav_food):
d[fav_food] = d[fav_food] + 1
else:
d[fav_food] = 1

d ends up being something like: {'pie': 400, 'pizza': 200, 'burgers':
100} if 400 people like pie, 200 like pizza and 100 like burgers.

There's nothing wrong (that I know of) by doing it as I have up there,
but is there a simpler, easier way? Looking forward to hearing about
how much of a n00b I am. Thanks in advance!
Er. OK so I realize now that I could have just done this:

d = {}
for person in people:
fav_food = person.fav_food
d[fav_food] = d.get(fav_food, 0) + 1

Jun 27 '08 #2
Zack <zh********@gmail.comwrites:
Given a bunch of objects that all have a certain property, I'd like to
accumulate the totals of how many of the objects property is a certain
value. Here's a more intelligible example:

Users all have one favorite food. Let's create a dictionary of
favorite foods as the keys and how many people have that food as their
favorite as the value.

d = {}
for person in People:
fav_food = person.fav_food
if d.has_key(fav_food):
d[fav_food] = d[fav_food] + 1
else:
d[fav_food] = 1
This is fine. If I wrote this, I'd write it like this:

d = {}
for person in people:
fav_food = person.fav_food
if fav_food in d:
d[fav_food] += 1
else:
d[fav_food] = 1

You can use d.get() instead:

d = {}
for person in people:
fav_food = person.fav_food
d[fav_food] = d.get(fav_food, 0) + 1

Or you can use a defaultdict:

from collections import defaultdict
d = defaultdict(int) # That means the default value will be 0
for person in people:
d[person.fav_food] += 1

HTH

--
Arnaud
Jun 27 '08 #3
Zack <zh********@gmail.comwrote:
There's nothing wrong (that I know of) by doing it as I have up there,
but is there a simpler, easier way? Looking forward to hearing about
how much of a n00b I am. Thanks in advance!
You want the defaultdict type:

import collections
d = collections.defaultdict(lambda: 0)
for person in People:
fav_food = person.fav_food
d[fav_food] += 1

New in Python 2.5, so if you require older Python versions, you
can't use that. Note also that this can become slow if most keys
are unique; the function given to defaultdict will be called the
first time a key is mentioned, and if the keys are mostly unique,
that will be the majority of the times, and calling a pure Python
function is fairly slow in CPython. (It probably won't matter
unless you have many thousands of unique keys, though.)
--
Thomas Bellman, Lysator Computer Club, Linköping University, Sweden
"If you ignore performance problems long enough, they ! bellman @
somehow seem to go away." -- Barry A Warsaw ! lysator.liu.se
Jun 27 '08 #4

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

Similar topics

5
by: Rakesh | last post by:
Hi, For a particular problem of mine, I want to sort <key, value> pairs by its value. Eg: Input: A, 4 B, 5
17
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...
7
by: ProvoWallis | last post by:
I'm still learning python so this might be a crazy question but I thought I would ask anyway. Can anyone tell me if it is possible to join two dictionaries together to create a new dictionary using...
3
by: mwt | last post by:
I want to set default values for a ConfigParser. So far, its job is very small, so there is only one section heading, . Reading the docs, I see that in order to set default values in a...
20
by: sucaba.r | last post by:
I've got a table that contains a column of accumulating uptime data that looks similar to this: 239.13 239.21 239.30 239.38 239.46 239.55 0.35
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...
4
by: O.B. | last post by:
I need the ability to parse through the values of a Dictionary and remove certain ones depending on their attribute values. In the example below, an InvalidOperationException is thrown in the...
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...
0
by: Maric Michaud | last post by:
Le Thursday 28 August 2008 03:43:16 norseman, vous avez écrit : Disctionaries are hash tables with a unique key and constant time lookup. What you want could be implemented as a complex data...
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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
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...
0
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
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.