Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!news.glorb.com!news-out.readnews.com!transit4.readnews.com!panix!gordon From: John Gordon Newsgroups: comp.lang.python Subject: Re: working with dict : incrementing dict dynamically Date: Mon, 11 Mar 2013 15:37:14 +0000 (UTC) Organization: PANIX Public Access Internet and UNIX, NYC Lines: 49 Message-ID: References: NNTP-Posting-Host: panix1.panix.com X-Trace: reader2.panix.com 1363016234 16475 166.84.1.1 (11 Mar 2013 15:37:14 GMT) X-Complaints-To: abuse@panix.com NNTP-Posting-Date: Mon, 11 Mar 2013 15:37:14 +0000 (UTC) User-Agent: nn/6.7.3 Xref: csiph.com comp.lang.python:41071 In inshu chauhan writes: > --14dae93408ffe4594104d7a7bf0c > Content-Type: text/plain; charset=ISO-8859-1 > I am trying to create a dictionary with a key and its values seraching from > a data set. But something is going wrong. This is the first time I am > working with dicts. > My code is : > import cv > def Computesegclass(segimage): > num_pixel = 0 > for y in xrange(0, segimage.height): > for x in xrange(0, segimage.width): > if segimage[y,x] == (0.0, 0.0, 0.0): > continue > else: > color = segimage[y,x] > blue = color[0] > green = color[1] > red = color[2] > region_num = blue + 256 * green + 65536 * red > print region_num > segments = dict({region_num : num_pixel}) You're creating a new segments dictionary for each pixel, overwriting the previous one. Instead, you probably want to create an empty dictionary at the top of your function. > if region_num == region_num: This if statement will always evaluate true, because you're comparing region_num to itself. > num_pixel = +1 This doesn't store the value of num_pixel in the dictionary. You probably want to do this instead: segments[region_num] += 1 -- John Gordon A is for Amy, who fell down the stairs gordon@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies"