Comparison of value items in a dictionary and counting matches

2024/10/14 21:24:09

Im using Python 2.7. Im trying to compare the value items in a dictionary.

I have two problems. First is the iteration of values in a dictionary with a length of 1. I always get an error, because python doesn't iterate integer and a single item as value is an integer for python. I have tried to change the item to a string. I have tried to change the whole dictionary to string. In these cases the iteration compares commas and brackets, as well and thats not the purpose. Therefore I duplicated the item. The values in key:1 and key:4 are one and the same item, two times. This solution works, but it changes a little bit the results, naturally.

The second problem is that the counting of matches doesn't work correctly. Yes, because of the first problem, but there is another one. My code compares all value items, with all other value items in the dictionary. Same moduls are not compared. If there is one match in a comparison, there is no problem. But if a comparison had two matches, the code will outputs the result two times as one match. But I want just one result, with two matches. The code includes many comments, so I hope you can unterstand it.

    #dicModul is a dictionary with the modulnames(keys of dictionary) and the components of the modul(value of dictionary).
# If a modul consists of one component, it is impossible to iterate the modul, therefore this component is two times in a modul.
# Any ideas how to iterate a single value item in a dictionary?
dicModul = {0:(0,1),1:(1,1), 2:(2,3,4,5,6,1,7,2), 3:(8,1),4:(9,9), 5:(10,10,5,11,0,12,13), 6:(10,11,9,7)}
#The list is needed for the iteration and to operate the different modul in the dictionary by following for loops.
ModulList = [0,1,2,3,4,5,6] 
#Counter is needed for counting same components in different moduls.
Counter = 0
for modKey in ModulList: #For-loop is needed for iteration of keysfor modKey2 in ModulList: #2nd for-loop of Modulkeys.The components of moduls have to be checked for matches in other moduls.#Therefore a second iteration of the modul list is needed.if modKey == modKey2: #Same moduls do not have to be checked.print "Skip same Moduls" Counter  = 0     #The modkey2 have to changed by iteration. The counter have to be reset.elif modKey != modKey2: #Different moduls have to be checked.for modVal in dicModul[modKey]:  #Iteration of components for iterated modul.if modVal in dicModul[modKey2]: #Checking iterated components in different modulCounter = Counter + 1  #If component was in different moduls, counter will add +1print "Modul: "+str(modKey)+" % Modul: "+str(modKey2)+ " Matches= "+str(Counter) #print function for both moduls and number of same components Counter =0

I think, if the can separte between the previous checked key and checked key at this juncture, the counter will not start at 0, every time. I tried to solve the problem and search for solutions, but I didn`t found this case.

loop on a dictionary (previous values) python

How to access previous/next element while for looping?

Count items in dictionary

I guess the solution have to look like the next code.
I mark my suggestion with #->

#dicModul is a dictionary with the modulnames(keys of dictionary) and the components of the modul(value of dictionary).
# If a modul consists of one component, it is impossible to iterate the modul, therefore this component is two times in a modul.
# Any ideas how to iterate a single value item in a dictionary?
dicModul = {0:(0,1),1:(1,1), 2:(2,3,4,5,6,1,7,2), 3:(8,1),4:(9,9), 5:(10,10,5,11,0,12,13), 6:(10,11,9,7)}
#The list is needed for the iteration and to operate the different modul in the dictionary by following for loops.
ModulList = [0,1,2,3,4,5,6] 
#Counter is needed for counting same components in different moduls.
Counter = 0
for modKey in ModulList: #For-loop is needed for iteration of keysfor modKey2 in ModulList: #2nd for-loop of Modulkeys.The components of moduls have to be checked for matches in other moduls.#Therefore a second iteration of the modul list is needed.if modKey == modKey2: #Same moduls do not have to be checked.print "Skip same Moduls" Counter  = 0     #The modkey2 have to changed by iteration. The counter have to be reset  elif modKey != modKey2: #Different moduls have to be checked.for modVal in dicModul[modKey]:  #Iteration of components for iterated modul.if modVal in dicModul[modKey2]: #Checking iterated components in different modul#->     if modKey2 == previous modKey2: #Checking if is the previous modul, so counter is not reset.#->           Counter = Counter +1 #->           print "Modul: "+str(modKey)+" % Modul: "+str(modKey2)+ " Matches= "+str(Counter) #->     else:#->        Counter = 1   #Counter is setted 1, because a same component is found in a different modul.elif:Counter = 0

This is my expected solution

Modul   Modul   Matches
skip same modul     
0   1   1
0   2   1
0   3   1
0   4   0
0   5   1
skip same modul     
1   2   1
1   3   1
1   4   0
1   5   0
skip same modul     
2   3   1
2   4   0
2   5   1
2   6   1
skip same modul     
3   4   0
3   5   0
skip same modul     
4   5   0
4   6   1
skip same modul     
5   6   3
Answer

I would recommend you take a look at for loops, and how they work. Codeacademy is a great (free) interactive resource. I'm not 100% sure I understand what you're asking, so I'm mainly going off of your question title. I think I understand what you're trying to do, but if I do, you're making it really difficult on yourself.

Iterating a dictionary with a single item:

dicty = {'a': 1}    
for key in dicty:print key

Iterating through values and keys in dictionaries:

for key, val in dicty.iteritems():print keyprint val

which is equivalent to:

for key in stuff:val = stuff[key]print keyprint val

Counting (key) matches in two dicts:

count = 0
keys_counted = []dicty_a = {'key1': 'val1', 'key2': 'val2'}
dicty_b = {'key1': 'val1', 'keyB': 'valB'}
for keyA, valA in dicty_a.iteritems():for keyB, valB in dicty_b.iteritems():if keyB == keyA and keyA not in keys_counted:count += 1keys_counted.append(valA)

The most common solution to making sure you don't duplicate a check is to build a list, check against it, then throw it out at the end. For example:

list_printed = []
for x in range(5):for y in range(5):if [x, y] not in list_printed:print x, ylist_printed.append([y,x])

outputs:

0 0
0 1
0 2
0 3
0 4
1 1
1 2
1 3
1 4
2 2
2 3
2 4
3 3
3 4
4 4

Enumerate() allows you to get both the keys and values of items in your dictionary, or the iteration number and value if you are looping through a list.

With regard to your issue with iterating over single items. Tuples are weird, especially with single items. You need the trailing comma or it's not a tuple, it's an int. Honestly, that strikes me as a bug, not a feature, but optimistically, it's probably important for some computer-sciency reason that's way beyond my paygrade. Also, the big thing that distinguishes lists [] and tuples () is that tuples are immutable. You probably don't need to be using tuples in this case. Having said that, you were getting your error just because, you said, you can't iterate an integer:

loopy = (1,)
for x in loopy:print x # this will _not_ raise an errorloopy = (1)
for x in loopy:print x # this _will_ raise an errorloopy = [1]
for x in loopy:print x # this will _not_ raise an errorloopy = 1
for x in loopy:print x # this _will_ raise an error

Applying this to what you're trying to do:

dicModul = {0:(0,1),1:(1,1), 2:(2,3,4,5,6,1,7,2), 3:(8,1),4:(9,9), 5:(10,10,5,11,0,12,13), 6:(10,11,9,7)}keys_checked = []def get_tuple_matches(t1, t2):counter = 0matched_list = []for x in t1:for y in t2:stuff = [x, y]if stuff not in matched_list and x == y:counter +=1matched_list.append(stuff)return counterfor key_outerloop, val_outerloop in dicModul.iteritems():for key_innerloop, val_innerloop in dicModul.iteritems():if key_outerloop == key_innerloop:print "skip..."elif [key_innerloop, key_outerloop] not in keys_checked:matches = get_tuple_matches(val_outerloop, val_innerloop)keys_checked.append([key_outerloop, key_innerloop])print "Modul: " + str(key_outerloop) + " | Modul: " + str(key_innerloop) + " | Matches= "+ str(matches)

output:

skip...
Modul: 0 | Modul: 1 | Matches= 1
Modul: 0 | Modul: 2 | Matches= 1
Modul: 0 | Modul: 3 | Matches= 1
Modul: 0 | Modul: 4 | Matches= 0
Modul: 0 | Modul: 5 | Matches= 1
Modul: 0 | Modul: 6 | Matches= 0
skip...
Modul: 1 | Modul: 2 | Matches= 1
Modul: 1 | Modul: 3 | Matches= 1
Modul: 1 | Modul: 4 | Matches= 0
Modul: 1 | Modul: 5 | Matches= 0
Modul: 1 | Modul: 6 | Matches= 0
skip...
Modul: 2 | Modul: 3 | Matches= 1
Modul: 2 | Modul: 4 | Matches= 0
Modul: 2 | Modul: 5 | Matches= 1
Modul: 2 | Modul: 6 | Matches= 1
skip...
Modul: 3 | Modul: 4 | Matches= 0
Modul: 3 | Modul: 5 | Matches= 0
Modul: 3 | Modul: 6 | Matches= 0
skip...
Modul: 4 | Modul: 5 | Matches= 0
Modul: 4 | Modul: 6 | Matches= 1
skip...
Modul: 5 | Modul: 6 | Matches= 2
skip...

code

https://en.xdnf.cn/q/117906.html

Related Q&A

how to send cookies inside post request

trying to send Post request with the cookies on my pc from get request #! /usr/bin/python import re #regex import urllib import urllib2 #get request x = urllib2.urlopen("http://www.example.com) #…

Flask-Uploads gives AttributeError?

from flask import Flask from flask.ext.uploads import UploadSet, configure_uploads, IMAGESapp = Flask(__name__)app.config[UPLOADED_PHOTOS_DEST] = /home/kevin photos = UploadSet(photos, IMAGES)configure…

Python: Alternate way to covert from base64 string to opencv

Im trying to convert this string in base64 (http://pastebin.com/uz4ta0RL) to something usable by OpenCV. Currently I am using this code (img_temp is the string) to use the OpenCV functions by convertin…

Move 3D plot to avoid clipping by margins

Im trying to figure out how I can get the 3D matplotlib images below to plot higher on the canvas so it doesnt get clipped. Here is the code Im using to create the plot. I couldnt find a way to attach …

HTML Link parsing using BeautifulSoup

here is my Python code which Im using to extract the Specific HTML from the Page links Im sending as parameter. Im using BeautifulSoup. This code works fine for sometimes and sometimes it is getting st…

XML format change using XSL file in a Python code

Have written a Python code to transform a XML file to a particular format using XSL stylesheet. Python code below:#!/usr/bin/env python # -*- coding:utf-8 -*- from lxml import etree def transform(xmlP…

How to extract a specific value from a dictionary in python

I want to extract distance from google distance matrix API in Python. The objet it returned is a python dictionary.{destination_addresses: [Mumbai, Maharashtra, India ],origin_addresses: [Powai, Mumbai…

label on top of image in python

I am trying to display text on top of an image. Right now the text is below the image or if I put a row=0 in the grid disappears. I am assuming it is behind the image. I cant seem to get it to work. My…

plot multiple graphs from multiple files gnuplot

I have a set of files named like this:qd-dPZ-z1-1nn.dat qd-dPZ-z2-1nn.dat qd-dPZ-z4-1nn.dat qd-dPZ-z8-1nn.dat qd-dPZ-z16-1nn.dat qd-dPZ-z32-1nn.dat qd-dPZ-z1-2nn.dat qd-dPZ-z2-2nn.dat qd-dPZ-z4…

Python writing to CSV... TypeError: coercing to Unicode: need string or buffer, file found

outputList is a list of lists. [ [a,b,c], [d,e,f], [g,h,i] ] and I want to output it to a csv file with each list as a separate row. Im getting this error TypeError: coercing to Unicode: need string or…