compare key and values at corresponding index in python - python

There is dictionary in python.key and value spelling is compared.if the mistake is greater than or equal to 2 than print incorrect
input={"their":"thuyr"}
output=incorrect(because t=t,h=h but e!=u,i!=y).
My problem is that i was unable to compare t==t,h==h,e==u,i==y.
The below code shows count value 22 but count value must be 2 because only two words mismatches with their
def find_correct(words_dict):
count=0
for key,value in words_dict.items():
for val in value:
for ky in key:
if(val!=ky):
count+=1
return count
print(find_correct({"their":"thuor"}))

It's because you're using nested loops. It's comparing each letter of "t" in "their" with each 5 letters in "thuor". Instead, just use a single loop like this:
def find_correct(words_dict):
count=0
for key,value in words_dict.items():
for val, ky in zip(value, key):
if(val!=ky):
count+=1
return count

Related

JSON File: Count the Full Number of Words with Python

For a current research project, I am planning to measure the relative occurrence of a unique word within a JSON file. Currently, I have an indicator for the number of unique words within the file and their corresponding number of occurrences (e.g. "technology":"325") but am still lacking a method for a full word count.
The code as I am using for a full word count (total = sum(d[key])) yields the following notification. I have checked some solutions for similar problems but not found an applicable answer yet. Is there any smart way to get this solved?
total = sum(d[key]) - TypeError: 'int' object is not iterable
The corresponding code section looks like this:
# Create an empty dictionary
d = dict()
# processing:
for row in data:
line = row['Text Main']
# Remove the leading spaces and newline character
line = line.strip()
# Convert the characters in line to
# lowercase to avoid case mismatch
line = line.lower()
# Remove the punctuation marks from the line
line = line.translate(line.maketrans("", "", string.punctuation))
# Split the line into words
words = line.split(" ")
# Iterate over each word in line
for word in words:
# Check if the word is already in dictionary
if word in d:
# Increment count of word by 1
d[word] = d[word] + 1
else:
# Add the word to dictionary with count 1
d[word] = 1
# Print the contents of dictionary
for key in list(d.keys()):
print(key, ":", d[key])
# Count the total number of words
total = sum(d[key])
print(total)
https://docs.python.org/3/library/functions.html#sum
You are trying to sum(iterable, /, start=0) an integer. This doesn't make sense, because sum is meant to be called on an iterable. A brief explanation of an iterable is that it's something that you could use a for loop on. For example, a list.
You could either modify your # Print the contents of dictionary loop in one of the two following ways:
# Print the contents of dictionary
total = 0
for key in list(d.keys()):
print(key, ":", d[key])
# Count the total number of words
total += d[key]
print(total)
print("Actual total: ," total)
Or, more condensed:
# Print the contents of dictionary
for key in list(d.keys()):
print(key, ":", d[key])
# Get the total word count
total = sum(d.values())
python's built-in sum function takes iterable as argument, but you trying to pass an single number to it. your code is equivalent to
total = sum(1)
but sum function need add something iterable to compute sum from. e.g.
sum([1,2,3,4,5,6,7])
if you want to compute total number of words you can try:
sum(d.values())
d=dict()
d['A']=1
d['B']=2
d['C']=3
total = sum(d.values())
print total
for key in list(d.keys()):
print(key, ":", d[key], float(d[key])/total)
#Count the total number of words
d[key] is a single int
d.values() is a list

Select dictionary keys and put them into a list

I would be very happy if somebody could help me solve the following exercise about dictionaries.
Write a function that takes a dictionary where every key is a string and the value is a whole number (integer) and returns a sorted list of the keys corresponding to their even numbers.
Example
dictionary = {'Kurt':35, 'Alex':26, 'Laura':31}
Should return
mylist= ['Alex'] # because it's the only key that has a matching even number
This is my code
def even_numbers (mydict):
mylist = []
for num in mydict.values():
if num % 2 == 0:
mylist.append(mydict.keys())
return mylist
Please help me
use dict.items instead of dict.values:
def even_numbers (mydict):
mylist = []
for key, num in mydict.items():
if num % 2 == 0:
mylist.append(key)
return mylist
when you do mylist.append(mydict.keys()) you'll have a list of keys for every pair value, so the need of using dict.items which return an iterable of key, value pair

counting the number of terms that are not repeated in the python list

the question was actually like
Write a program that says the number of terms to be replaced to get all the numbers same in the list
ex
a=[1,1,2,1,1,4,1,1]
then the expected output is 2
I guess you are looking for the minimum number of numbers to be replaced so that all numbers are the same.
# store occurrences of each number in a dictionary
d = {}
for i in a:
if i not in d:
d[i] = 1
else:
d[i] += 1
# get key with max value: i.e. most frequent number in initial list
max_k = max(d, key=d.get)
# delete element that appears most often in the initial list
del d[max_k]
# count rest of the numbers => numbers to be replaced
nums_to_replaces = sum([d[k] for k in d])
Your wording is a bit strange.
If you want the number of items that are not one:
len([i for i in a if i!=1])
or
len(a)-a.count(1)
if you want the unique set of numbers that are not repeated as the question says:
len([i for i in set(a) if a.count(i)==1])
You could iterate over the list and make a dictionary of the occurrence:
occurrences = {}
for x in range(len(a)):
if a[x] not in occurences:
occurrences[x] = 1
else:
occurrences[x] += 1
Now you could have a dict of the occurrences and you could do this to get the number of terms to be replaced:
nums = list(occurrences.values()).sort(reverse=True) # Sort I descending order with num of repetitions
print(sum(nums[1:])) # Add occurrences of all but the element with max occurrences
#Or just subtract the max occurrence from the length of list
print(len(a) - max(list(occurrences.values())))
This will give you the least number of changes need to be made. In this way you cannot specify which element you want the whole list to contain

Manipulation Searching Dictionary with list as value in Python

I have a dictionary like this:
d={1:[2,3,4],2:[1,3,4],3:[1,2],4:[1,2,3]}.
I need to do for example: In the key 1 I have the list [2,3,4]. I have to count the number of connections between the element of the list as value in all the keys.
So I have to verify if in key 2 there are as elements 3or 4 and also the key 3with the element 4.
This research has to continue for all the key of the dictionary d.
At the end of searching in all the keys, I had to count the number of the couples found. In the example I have only count=2 because key 2 is connected with 3 and 4, but 3 isn't connected to 4. Repetitions aren't required. So I'm not interested in the couple 4-2 if I had already found (and counted) the couple 2-4.
I tried to implement for the first key:
`
d={}
d={1:[2,3,4],2:[1,3,4],3:[1,2],4:[1,2,3]}
values=[]
count = 0
#for key in d:
values = d[1]
for value in values:
for i in (d[value]):
print "i: ",i
if i in values:
count += 1
print " count: ", count
print ".........."
print(count)
`
But, in this way count=5 because it count also the reversed couples. I have to specify something so count will be count=3. How can do that?
d={}
d={1:[2,3,4],2:[1,3,4],3:[1,2],4:[1,2]}
print d
values=[]
for key in d:
count = 0
values = d[key]
for value in values:
for i in (d[value]):
if i in values:
count += 1
print "count: ",count/2, " key: ", key

Python - dictionary print the key as many times as his value

I want to print out all the letters in my dictionary (seen at the last line of my code) the problem is that the output is aqlmui now. But as you guys can see the l in my dictionary is having a value of 2 so I want to print that out 2 times. so the output of my program should be: aqllmui.
Help would be appreciated a lot! :)
def display_hand(hand):
row = ''
for letter in hand:
row += letter
#I think i need to put an if statement here but I just don't know how to do it
print row
display_hand({'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1})
You can also try print "".join(k*v for (k,v) in s.iteritems()).
Here k*v for (k,v) in s.iteritems() returns a list of key*value like ["a","i","m","ll","q","u"] and "".join(list) will join that list to make a string.
just do:
row += letter * hand[letter]
You can use string/int multiplication to perform multiple concatenations
for letter in hand:
row += letter * hand[letter]
Or a little more clearly and efficiently:
for letter, count in hand.iteritems(): # Use hand.items() in Python 3
row += letter * count

Categories

Resources