List of Starters in dictionaries - python-3.x

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)

Related

Python: Print stuff in dictionary line by line

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.

Can't figure out how to print out all the integers in my dictionary value list

Curious if there is any way to do something similar to this.
Dictionary = {"item":1,"item2":[1,2,3,4]}
for keys,values in Dictionary.items():
if values == list():
print(values[0:3])
With the resulting outcome of
1
2
3
4
Sure, there is:
Dictionary = {"item": 1, "item2": [1,2,3,4]}
for values in Dictionary.values():
if type(values) == list:
for item in values:
print(item, end=' ')

Reading input as dictionary in python

Im trying to read input spread across multiline in form of dictionary and apply simple math operations on the value of dictionary . My code reads
d ={}
bal=0
text = input().split(",") #split the input text based on line'text'
print(text)
for i in range(5):
text1 = text[i].split(" ") #split the input text based on space & store in the list 'text1'
d[text1[0]] = int(text1[1]) #assign the 1st item to key and 2nd item to value of the dictionary
print(d)
for key in d:
if key=='D':
bal=bal+int(d[key])
#print(d[key])
elif key=='W':
bal=bal-int(d[key])
print(bal)
Input : W 300,W 200,D 100,D 400,D 600
output :{'D': 600, 'W': 200}
400
Expected Output: {'W':300,'W':200,'D':100,'D':400,'D':600}
600
ISSUE: The issue here is the code always reads 2 and last values only . For example in the above case output is
{'D': 600, 'W': 200}
400
Can someone let me know the issue with for loop .
Thanks in advance
You can try like this in a simpler way using your own approach. #Rakesh and #Sabesh suggested good. Dictionary is an unordered collection with unique and immutable keys. You can easily check this on your Python interactive console by executing help(dict).
You can check https://docs.python.org/2/library/collections.html#collections.defaultdict . Here you'll find number of examples on how to efficiently using dictionary.
>>> d = {}
>>> text = 'W 300,W 200,D 100,D 400,D 600'
>>>
>>> for item in text.split(","):
... arr = item.split()
... d.setdefault(arr[0], []).append(arr[1])
...
>>> d
{'W': ['300', '200'], 'D': ['100', '400', '600']}
>>>
>>> w = [int(n) for n in d['W']]
>>> d = [int(n) for n in d['D']]
>>>
>>> bal = sum(d) - sum(w)
>>> bal
600
>>>

Mathematical operation on a dictionary list (Python 3.6)

I am using Python 3.6 and I have a list of dictionaries like this:
list = [{'name': 'A', 'number':'1'}, {'name': 'B', 'number':'2'}, {'name': 'C', 'number':'3'}, {'name': 'D', 'number':'4'}]
I found out how to print the list in the desired format with:
for s in list:
name = s['name']
number = s['number']
print(name + " = "+ number)
Which gives:
A = 1
B = 2
C = 3
D = 4
I would like to be able to multiply the items 'number' by 2 for example and display:
A = 2
B = 4
C = 6
D = 8
Thank you!
Are you trying to temporarily multiply the values and print them out? Which in this case, you would change your last line to
print(name + " = "+ int(number) * 2)
However, if you want to multiply the values in your dictionary directly, you would go about it as so:
for s in list:
name = s['name']
s['number'] = str(int(s['number']) * 2) # multiply value by 2
number = s['number']
print(name + " = "+ number)
Note that your problem may arise from the fact that your dictionary values are stored as strings instead of integers, which means that to perform any kind of mathematical operation on them, you must convert them to an integer and back to a string.
You're able to multiply a number by using the * symbol 2 * 2 will output 4.
Because your values are stored as Strings you'll need to convert them to Integers first. int('2') * 2 == 4.
Then to print an Integer with a string you need to convert it back to a string.
for the last line change it to
print(name + " = "+ str(int(number)*2))
You can always iterate over your list to modify the value of its nested parts, i.e.:
your_list = [{'name': 'A', 'number': '1'},
{'name': 'B', 'number': '2'},
{'name': 'C', 'number': '3'},
{'name': 'D', 'number': '4'}]
for item in your_list: # iterate over each dictionary in your_list
# since your dict contains strings we have to convert the value into a number/integer
# before multiplying it by 2
item["number"] = int(item["number"]) * 2 # turn it back to a string with str() if needed
# now, let's demonstrate that the data changed in `your_list`:
for item in your_list: # iterate over each dictionary in your_list
print("{} = {}".format(item["name"], item["number"])) # print in your desired format
# A = 2
# B = 4
# C = 6
# D = 8

Python string duplicates

I have a list
a=['apple', 'elephant', 'ball', 'country', 'lotus', 'potato']
I am trying to find largest element in the list with no duplicates.
For example script should return "country" as it doesn't have any duplicates.
Please help
You could also use collections.Counter for this:
from collections import Counter
a = ['apple', 'elephant', 'ball', 'country', 'lotus', 'potato']
a = set(a)
no_dups = []
for word in a:
counts = Counter(word)
if all(v == 1 for v in counts.values()):
no_dups.append(word)
print(max(no_dups, key = len))
Which follows this procedure:
Converts a to a set, since we only need to look at a word once, just in case a contains duplicates.
Creates a Counter() object of each word.
Only appends words that have a count of 1 for each letter, using all().
Get longest word from this resultant list, using max().
Note: This does not handle ties, you may need to do further work to handle this.
def has_dup(x):
unique = set(x) # pick unique letters
return any([x.count(e) != 1 for e in unique]) # find if any letter appear more than once
def main():
a = ['apple', 'elephant', 'ball', 'country', 'lotus', 'potato']
a = [e for e in a if not has_dup(e)] # filter out duplicates
chosen = max(a, key=len) # choose with max length
print(chosen)
if __name__ == '__main__':
main()

Resources