473,651 Members | 2,659 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

dict invert - learning question

Hello,

here is a piece of code I wrote to check the frequency of values and
switch them around to keys in a new dictionary. Just to measure how
many times a certain key occurs:

def invert(d):
inv = {}
for key in d:
val = d[key]
if val not in inv:
inv.setdefault( val, [key])
else:
inv[val].append(key)
return inv
Using the methods above (I'm just a beginner) could I have written it
more concisely? Any criticism/critique in the code would be greatly
appreciated.

Many Thanks,

dave

Jun 27 '08 #1
4 1712
dave <sq************ *@y1a2hoo3.comw rote:
Hello,

here is a piece of code I wrote to check the frequency of values and
switch them around to keys in a new dictionary. Just to measure how
many times a certain key occurs:

def invert(d):
inv = {}
for key in d:
val = d[key]
if val not in inv:
inv.setdefault( val, [key])
else:
inv[val].append(key)
return inv
Using the methods above (I'm just a beginner) could I have written it
more concisely? Any criticism/critique in the code would be greatly
appreciated.
The obvious change I'd make is:
if val not in inv:
inv[val] = key
else:
... etc.

The setdefault method is only appropriate if you don't know
whether or not the key is in the dictionary. since you've already tests
that you should just go ahead and set the value.
Otherwise it all seems fine.
Jun 27 '08 #2
Assuming all the values are unique:
>>a={1:'a', 2:'b', 3:'c'}
>>dict(zip(a.ke ys(), a.values()))
{1: 'a', 2: 'b', 3: 'c'}

The problem is you obviously can't assume that in most cases.

Still, zip() is very useful function.
Jun 27 '08 #3
On 4 Maj, 01:27, mrk...@gmail.co m wrote:
>a={1:'a', 2:'b', 3:'c'}
Oops, it should obviously be:
>>dict(zip(a.va lues(), a.keys()))
{'a': 1, 'c': 3, 'b': 2}

Jun 27 '08 #4
On Sat, May 3, 2008 at 4:29 PM, dave <sq************ *@y1a2hoo3.comw rote:
here is a piece of code I wrote to check the frequency of values and switch
them around to keys in a new dictionary. Just to measure how many times a
certain key occurs:

def invert(d):
inv = {}
for key in d:
val = d[key]
if val not in inv:
inv.setdefault( val, [key])
else:
inv[val].append(key)
return inv
Using the methods above (I'm just a beginner) could I have written it more
concisely? Any criticism/critique in the code would be greatly appreciated.
If you're using python 2.5, the collections module has the defaultdict
type that is useful for things like this.

from collections import defaultdict

def invert2(d):
inv = defaultdict(lis t)
for key, value in d.items():
inv[value] += key
return dict(inv)

If you don't mind returning a defaultdict instead of a regular
dictionary, you could just 'return inv'. The defaultdict is useful
for building up the frequency counts in the first place too:

def wordcount(wordl ist):
wc = defaultdict(int )
for word in wordlist:
wc[word] += 1
return dict(wc)
--
Jerry
Jun 27 '08 #5

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

Similar topics

9
12232
by: Robin Cull | last post by:
Imagine I have a dict looking something like this: myDict = {"key 1": , "key 2": , "key 3": , "key 4": } That is, a set of keys which have a variable length list of associated values after them. What I want to do is filter out a subset of this dict to produce another dict that satisfies a set of criteria (in this case whether it contains all four values) to end up with something
2
2150
by: GrelEns | last post by:
hello, i would like if this behaviour can be obtained from python : trap an attributeError from inside a subclassing dict class... (here is a silly examples to explain my question) class Test(dict): """subclassing a dict and each key will permit access to a tuple of fized size""" def __init__(self):
7
3094
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
2444
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 function), I've been finding myself lately using it sometimes instead of dict literals, for no particular reason. Is there any coding style consensus on when should dict literals be preferred over dict(**kwds) and vice versa ? George
41
3362
by: rick | last post by:
Why can't Python have a reverse() function/method like Ruby? Python: x = 'a_string' # Reverse the string print x Ruby: x = 'a_string' # Reverse the string
1
2891
by: mahesh.nimbalkar | last post by:
Hi, I have color as System.Drawing.Color c1 object as background color. Now I would like to get another System.Drawing.Color c2 object which is invert of c1 color to be used as foreground color. e.g if I have c1 as black and I should get c2 as white.
0
2241
by: Karthik | last post by:
Hi, I want to record a sound wave from a mic and at the same time invert it and play the inverted wave.My code goes as follows, however nothing is written into the E:\inverted.wav file.Thanks in advance for any help. from Tkinter import * root = Tk() import tkSnack tkSnack.initializeSnack(root)
13
1491
by: Pat | last post by:
I can't figure out how to set up a Python data structure to read in data that looks something like this (albeit somewhat simplified and contrived): States Counties Schools Classes Max Allowed Students Current enrolled Students
12
5002
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 of the old dict a list of the keys of the old dict that have that very value.
0
8347
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8694
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8571
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7294
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6157
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5605
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4143
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4280
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2696
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.