Python: Print stuff in dictionary line by line - python-3.x

I have an assignment where If I input a string for example
food food games hi food
it would print out like this:
food: 3
games: 1
hi: 1
the code I made right now is
def count_word(string1):
counts = {}
words = string1.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
string1 = str(input())
print(count_word(string1))
If I input the same string as above it prints out:
{'food': 3, 'games': 1, 'hi': 1}
how do I make it so it prints out like this:
food: 3
games: 1
hi: 1

Following should work:
d = {'food': 3, 'games': 1, 'hi': 1} # generated by counter function
for word, count in d.items():
print(f'{word}: {count}')
if you want this sorted alphabetically replace d.items() with sorted(d.items()).

dsic = {'food': 3, 'games': 1, 'hi': 1}
you could try somthing like this maybe:
import json
print(json.dumps(dsic, sort_keys=False, indent=4))
or this one:
for i,x in dsic.items():
print(str(i)+': ' + str(x))

You should do your research before posting on stackoverflow.
For now, Hint is to use two loops. One for the list and one for printing the string.

Related

List of Starters in dictionaries

in the given method called solve which takes as parameter a list of strings called items.
You have to print the list of items for each alphabet. Print in sorted order of alphabets.
Example Input:
noodles, rice, banan, sweets, ramen, souffle, apricot, apple, bread
Output:
a : apple apricot
b : banana bread
n : noodles
r : ramen rice
s : souffle sweets
import collections
def solve(items):
result = {}
for word in items:
char = word[0]
if char in result:
result[char].append(word)
else:
result[char] = [word]
od = collections.OrderedDict(sorted(result.items()))
for key, value in od.items():
print ("%s : %s"%(key,value))
but, im getting it in brakets...! not like a desired output...
Alternatively you can try to leverage Python collections.defaultdict as this will simply the code logic:
You could convert this easily to the function - maybe as an exercise? If you have any questions, please ask.
from collections import defaultdict
inputs = "noodles, rice, banan, sweets, ramen, souffle, apricot, apple, bread"
groups = defaultdict(list)
lst = inputs.split(', ')
#print(lst)
for item in lst:
groups[item[0]].append(item)
for k, val in sorted(groups.items()):
print(k, ": ", *val) # *val to expand the list content
Output:
a : apricot apple
b : banan bread
n : noodles
r : rice ramen
s : sweets souffle
You are not performing any comparisons to find the maxEnglish or the maxTotalMarks. The reason print('Max Marks:',d['name']) is printing the correct result is because Dwight is the last entry in the Ordered Dictionary and you are printing the last item's name.
One of the ways you could tackle this question is by keeping variables that keep track of the maximum scores and as you iterate through the dictionary, you can compare against these stored value to determine if the current value
that you are iterating is greater or lesser than all the values that you have seen so far. Something like this:
def solve(stats):
maxEnglishMarks = -1
maxTotalMarks = -1
maxEnglishStudentName = maxTotalStudentName = None
for stat in stats:
totalMarks = sum([i for i in stat.values() if str(i).isnumeric() == True])
if totalMarks > maxTotalMarks:
maxTotalStudentName = stat['name']
maxTotalMarks = totalMarks
if stat['English'] > maxEnglishMarks:
maxEnglishStudentName = stat['name']
maxEnglishMarks = stat['English']
print('Max English:', maxEnglishStudentName)
print('Max Marks:', maxTotalStudentName)
stats = [
{'name': 'Jim', 'English': 92, 'Math': 80, 'Physics': 70},
{'name': 'Pam', 'French': 72, 'English': 80, 'Biology': 65},
{'name': 'Dwight', 'Farming': 95, 'English': 85, 'Chemistry': 97}
]
solve(stats)

Rewrite word count function as OOP in python 3

I have written a simple function for counting the occurrences of words in a sentence or phrase.
def count(phrase):
phrase = phrase.lower()
lst = phrase.split()
dct = dict()
for word in lst:
if word not in dct:
dct[word] = 1
else:
dct[word] += 1
return dct
Note that right now I'm not concerned with punctuation, numbers, or stopwords.
What I want to do is write a class to take an object and do the same thing. Here's what I have so far, but now I'm stuck on how to pass the list on to the loop that counts and creates the dictionary:
class Count:
dct = dict()
def __init__(self, phrase):
self.phrase = phrase
def lst(self):
return self.phrase.lower().split()
You can use defaultdict for convenience.
from collections import defaultdict as ddict
class Count:
def __init__(self, phrase):
self.phrase = phrase
self.dct = ddict(int)
def lst(self):
return self.phrase.lower().split()
# you can do it this way
def make_dict(self):
lst_words = self.lst()
for word in lst_words:
self.dct[word] += 1
c = Count("What I want to do is write a class to take an object and do the same thing. Here's what I have so far, but now I'm stuck on how to pass the list on to the loop that counts and creates the dictionary")
c.make_dict() # make a dictonary out of words
c.dct # display the contents stored in the dict
Output:
defaultdict(int,
{'what': 2,
'i': 2,
'want': 1,
'to': 4,
'do': 2,
'is': 1,
'write': 1,
'a': 1,
'class': 1,
'take': 1,
'an': 1,
'object': 1,
'and': 2,
'the': 4,
'same': 1,
'thing.': 1,
"here's": 1,
'have': 1,
'so': 1,
'far,': 1,
'but': 1,
'now': 1,
"i'm": 1,
'stuck': 1,
'on': 2,
'how': 1,
'pass': 1,
'list': 1,
'loop': 1,
'that': 1,
'counts': 1,
'creates': 1,
'dictionary': 1})
Update:
By the courtesy Roelant of there is one more way to do the same thing, using Counter.
from collections import Counter
class Count:
def __init__(self, phrase):
self.phrase = phrase
self.dct = None
def lst(self):
return self.phrase.lower().split()
# you can do it this way also.
def make_dict(self):
lst_words = self.lst()
self.dct = Counter(lst_words)
Just note that you can use collections.Counter for this; maybe you know this allready, but I'll put this option here anyways.
>>> import collections
>>> phrase = "What I want to do is write a class to take an object and do the same thing. Here's what I have so far, but now I'm stuck on how to pass the list on to the loop that counts and creates the dictionary."
>>> c = collections.Counter(phrase.lower().split())
>>> for k, v in c.most_common():
... print(v, k)
4 to
4 the
2 what
2 i
2 do
2 and
2 on
1 want
1 is
1 write
1 a
1 class
1 take
1 an
1 object
1 same
1 thing.
1 here's
1 have
1 so
1 far,
1 but
1 now
1 i'm
1 stuck
1 how
1 pass
1 list
1 loop
1 that
1 counts
1 creates
1 dictionary.
There is no big advantage of wrapping this in a class, but you could have something simple like this that subclasses Counter:
import collections
import string
class MyCounter(collections.Counter):
def __init__(self, phrase):
# do some preprocessing, for example removing puntuation
phrase = ''.join(
c.lower()
for c in phrase
if c not in string.punctuation)
super().__init__(phrase.split())
The use would be similar as before:
>>> mc = MyCounter(phrase) # 'lower' and 'split' is done inside
>>> for k, v in mc.most_common():
... print(v, k)
4 to
4 the
2 what
2 i
2 do
2 and
2 on
1 want
1 is
1 write
1 a
1 class
1 take
1 an
1 object
1 same
1 thing
1 heres
1 have
1 so
1 far
1 but
1 now
1 im
1 stuck
1 how
1 pass
1 list
1 loop
1 that
1 counts
1 creates
1 dictionary

Print nested dictionary in python3

How can I print a nested python dictionary in a specific format?
So, my dictionary is looks like this:
dictionary = {'Doc1':{word1: 3, word2: 1}, 'Doc2':{word1: 1, word2: 14, word3: 3}, 'Doc3':{word1: 2}}
I tried the following way:
for x, y in dictionary.items():
print(x,":", y)
But it will printL`
Doc1: {word1:3, word2: 1}
Doc2: {word1:1, word2:14, word3:3}
Doc3: {word1:2}
How to get rid of the bracket and print the plain information?
I want to print on the following format:
Doc1: word1:3; word2:1
Doc2: word1:1; word2:14; word3: 3
Doc3: word1:2;
:
in your case 'y' is a dict, so if you want to print it differently you can override the repr (representation of the object) or dict.
alternatively you can use some recursion here
def print_d(dd):
if type(dd) != dict:
return str(dd)
else:
res = []
for x,y in dd.items():
res.append(''.join((str(x),':',print_d(y))))
return '; '.join(res)
if __name__=='__main__':
dictionary = {'Doc1':{'word1': 3, 'word2': 1}, 'Doc2':{'word1': 1, 'word2': 14, 'word3': 3}, 'Doc3':{'word1': 2}}
for x, y in dictionary.items():
print(x,": ", print_d(y))
Aside from the fact that your original dictionary declaration is not valid python unless each word is a defined variable, this seems to work:
import json
print(json.dumps(dictionary).replace("{","").replace(',','').replace("}","\n").replace('"',''))
Result:
Doc1: word1: 3 word2: 1
Doc2: word1: 1 word2: 14 word3: 3
Doc3: word1: 2

Using python need to get the substrings

Q)After executing the code Need to print the values [1, 12, 123, 2, 23, 3, 13], but iam getting [1, 12, 123, 2, 23, 3]. I have missing the letter 13. can any one tell me the reason to overcome that error?
def get_all_substrings(string):
length = len(string)
list = []
for i in range(length):
for j in range(i,length):
list.append(string[i:j+1])
return list
values = get_all_substrings('123')
results = list(map(int, values))
print(results)
count = 0
for i in results:
if i > 1 :
if (i % 2) != 0:
count += 1
print(count)
Pretty straight forward issue in your nested for loops within get_all_substrings(), lets walk it!
You are iterating over each element of your string 123:
for i in range(length) # we know length to be 3, so range is 0, 1, 2
You then iterate each subsequent element from the current i:
for j in range(i,length)
Finally you append a string from position i to j+1 using the slice operator:
list.append(string[i:j+1])
But what exactly is happening? Well we can step through further!
The first value of i is 0, so lets skip the first for, go to the second:
for j in range(0, 3): # i.e. the whole string!
# you would eventually execute all of the following
list.append(string[0:0 + 1]) # '1'
list.append(string[0:1 + 1]) # '12'
list.append(string[0:2 + 1]) # '123'
# but wait...were is '13'???? (this is your hint!)
The next value of i is 1:
for j in range(1, 3):
# you would eventually execute all of the following
list.append(string[1:1 + 1]) # '2'
list.append(string[1:2 + 1]) # '23'
# notice how we are only grabbing values of position i or more?
Finally you get to i is 2:
for j in range(2, 3): # i.e. the whole string!
# you would eventually execute all of the following
list.append(string[2:2 + 1]) # '3'
I've shown you what is happening (as you've asked in your question), I leave it to you to devise your own solution. A couple notes:
You need to look at all index combinations from position i
Dont name objects by their type (i.e. dont name a list object list)
I would try something like this using itertools and powerset() recipe
from itertools import chain, combinations
def powerset(iterable):
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))
output = list(map(''.join, powerset('123')))
output.pop(0)
Here is another option, using combinations
from itertools import combinations
def get_sub_ints(raw):
return [''.join(sub) for i in range(1, len(raw) + 1) for sub in combinations(raw, i)]
if __name__ == '__main__':
print(get_sub_ints('123'))
>>> ['1', '2', '3', '12', '13', '23', '123']

Using Python and Flask

Python with Flask
This is my code:
word=input("Type Something: ")
listofwords=word.split()
wordfreq = []
for w in listofwords:
wordfreq.append(listofwords.count(w))
print("Word: "+str(listofwords)+ "\n")
print("Count: "+str(wordfreq) + "\n")
My code works fine. My only problem is that it prints it out horizontally:
Word: ['is', 'the', 'bus', 'at', 'the', 'terminal']
Count: [1, 2, 1, 1, 2, 1]
How do I have my results printout vertically like this:
Word Count
"is" 1
"the" 2
"bus" 1
"at" 1
"the" 2
"terminal" 1
Also, which parts of my code should I put under "tr" and "td" in the table section of my html. I already have Word and Count under "th" and it works fine.
In python 3.x: You must call additional the function:
print()
For example:
for w in listofwords:
wordfreq.append(listofwords.count(w))
print("Word: "+str(listofwords))
print()
print("Count: "+str(wordfreq))
print()
More information you can get here.

Resources