bag contains:
['Item','item','item']
coins contains:
['Item','Item','Item']
coin_to_bag = {}
print('Here are your bags:\n')
print(bags)
print('\n')
print('Here are your coin types:\n')
print (coins)
my nested loop
bags = ['small', 'medium','large']
coins = ['quarter', 'dime', 'nickel', 'penny']
'''
what Im trying to do:
foreach bag in bags:
print: enter in a coin index. e.g. 1 for quarter out of ['quarter', 'dime', 'nickel', 'penny']
prompt:: how many of this type? 15 (thus will store '15' representing, there are 15 quarters, storing '15')
for index_position in coins:
assign index, type = bag create a dictionary like ["quarter"] = {"1", "15"}}
print(coin_to_bag)
'''
for bag in bags:
coin_to_bag = coin_to_bag[bag] # set quarter as a key in coin_to_bag = {["quarter"]}
coin_type = input('Number of this type? e.g. type 1 for Quarter "["Quarter", "Nickel"]" ') #e.g. 0.25 * 2
coin_amount = input('Number of this type? e.g. 15') #e.g. 0.25 * 2
for coin in coins:
#set values for key: quarter like {["quarter"] = ["1", "15"]}
coin_to_bag[bag] = coin_to_bag[coin_type], coin_to_bag[coin_amount]
print(coin_to_bag)
I can't seem to figure out how to use my dictionary and lists(coin,bags)
Ultimately I'm trying to get coin_to_bag to store:
coin_to_bag = {"small": {"1", "15"}, "medium": {"2", "5"} }
Values are stored to dictionaries in this way:
some_dict = {}
some_dict[key] = value
Or in one line as: some_dict = {key: value}.
So presumably, you want:
coin_to_bag[bag] = [coin_type, coin_amount]
For example this might mean,
coin_to_bag['small'] = ["1", "15"]
Doing this, coin_to_bag[bag] means access the element of the coin_to_bag dictionary with the key given by bag. But that key-value won't exist until you set it.
Related
I'm pretty new to programming and I'm starting with python
Why is it that the 'for' loop is iterating over the list and not over the key of the dictionary?
The intention is that the loop iterates over the list but I don't understand why it's happening if 'for' loops are supposed to iterate over the keys and not over the values
def getUserData():
D = {}
while True:
studentId = input("Enter student ID: ")
gradesList = input("Enter the grades by comma separated values: ")
moreStudents = input("Enter 'no' to quit insertion or 'yes' to add more student info: ")
if studentId in D:
print(studentId, "is already inserted")
else:
D[studentId] = gradesList.split(",")
if moreStudents.lower() == "no":
return D
elif moreStudents.lower() == "yes":
pass
studentData = getUserData()
def getAvgGrades(D):
avgGrades = {}
for x in D:
L = D[x] <------------------- #This is specifically what I don't understand
s = 0
for grades in L:
s = s + int(grades)
avgGrades[x] = s/len(L)
return avgGrades
avgG = getAvgGrades(studentData)
for x in avgG:
print("Student:", x, "got avg grades as: ", avgG[x])
A for loop iterates over the keys of a dict. So this code:
for x in D:
L = D[x]
Means that x is each key from the D.
Then L = D[x] fetches the corresponding list generated previously: D[studentId] = gradesList.split(",")
Better would be to iterate over the keys and values at once:
for x,L in D.items():
s = 0
...
When you iterate over a dict like so:
for x in D:
You actually do this:
for x in D.keys(): # you iterate over the keys
To get the key and the value, simply do this:
for k, v in D.items():
I have a list of keyword frequency as the following, the frequency is counted by matching the keyword to the responses. However, I want to remove the frequency of "public health", "health issue", and "health condition" from "health". Also, remove the frequency of "public health officials" from the "public health". I am wondering, how can I do this in Python?
keyword
frequency
health
56
healthcare
23
health condition
5
health issue
4
public health
7
public health official
2
Build on the previous answer, I figure it out as the following:
Tokenize the keyword and find the max keyword length
Loop through the keyword column from the max length to a single word
Remove duplicated keyword frequency if keywords with smaller length appear within a
bigger keyphrase
Update the previous dataframe
import pandas as pd
import numpy as np
import spacy
import en_core_web_md
nlp = en_core_web_md.load()
df = .....
df_3 = df
# find the max length of the column value
max_length = df["keyword"].map(lambda x: len(nlp(x))).max()
length = max_length
# loop until the length ends with column value that only have one word
while length > 1 :
element = []
value = []
element_2 = []
value_2 = []
element_3 = []
value_3 = []
# select column value by different length
for index, row in df_3.iterrows():
a = len(nlp(row["keyword"]))
if a == length:
element.append(row["keyword"])
value.append(row["frequency"])
if a < length:
element_2.append(row["keyword"])
value_2.append(row["frequency"])
if a > length:
element_3.append(row["keyword"])
value_3.append(row["frequency"])
d_1 = dict(zip(element, value))
d_2 = dict(zip(element_2, value_2))
d_3 = dict(zip(element_3, value_3))
# remove duplicated keyword frequency if keyword with smaller length
appear in key phrase with bigger length
for key1, value1 in d_1.items():
for key2, value2 in d_2.items():
if key2 in key1:
d_2[key2] = value2-value1
new_key = []
new_value = []
# update the original dataframe
for key, value in d_2.items():
new_key.append(key)
new_value.append(value)
for key, value in d_1.items():
new_key.append(key)
new_value.append(value)
for key, value in d_3.items():
new_key.append(key)
new_value.append(value)
df_3 = pd.DataFrame({"keyword":new_key, "frequency":new_value})
length -= 1
The answer looks pretty dump, welcome one more elegant~
With this script, you can specify the value to substract from with the variable ele.
Then every element that starts with the ele will be substracted.
For public health, you would just mirror the same code with a ele = "public health" before.
d = {
"health" : 56,
"healthcare" : 23,
"health condition" : 5,
"health issue" : 4,
"public health" : 7,
"public health official" : 2,
}
ele = "health"
for key, value in d.items():
if (key != ele) or not key.startswith("ele"):
d[ele] -= value
print(d[ele]) #-41
Everything is working for me in this program except for one thing; I need my output to group the names and values together in the print(names, "\n" values) section.
For example: Pat : €99, Kev : €55, Dermot : €100.
My code is below:
salesperson = int(input("How many salesperson's do you wish to account
for:"))
names = []
values = []
counter = 0
total_sales = 0
total_value = 0
if salesperson > counter:
while salesperson != counter:
name = input("Please enter in the salesperson's name:")
value = float(input("Please enter in the value of sales for the
salesperson:"))
salesperson -= 1
names.append(name)
values.append(value)
total_value += value
from statistics import mean
average_values = mean(values)
minimum = min(values)
maximum = max(values)
print(names,"\n",values)
print(average_values)
print(total_value)
print(minimum)
print(maximum)
You can do this using zip(), and f-strings:
print([f"{x}: £{y}" for x, y in zip(names,values)])
Output:
['Pat: £1.0', 'Dermot: £2.0', 'Kev: £3.0', 'Boris: £4.0', 'Jeremy: £5.0']
I have a table as such representing the result of a game.
GameTab = [['TRE','ARD','1','1'],['PRK','GEA','2','3'],['ARD','PRK','1','0'],['TRE','GEA','2','1']]
I appended the result from a text file into table form so here's the text format: To put it easier, it's interpreted in such that for example, TRE scored 1 and ARD scored 1. PRK scored 2 and GEA score 3.
TRE:ARD:1:1
PRK:GEA:2:3
ARD:PRK:1:0
TRE:GEA:2:1
Instead of obtaining the result for the player, i want to obtain the result of the opponent instead. I have done my code in a way where it obtains the result of the player but i couldn't think of a way to obtain the opponents result.
For example, in the match of PRK:GEA and TRE:GEA:
The opponent of GEA scored a total of: 4
My code:
gameTab =[['TRE','ARD','1','1'],['PRK','GEA','2','3'],['ARD','PRK','1','0'],
['TRE','GEA','2','1']]
dictionary = {}
for i in gameTab:
for c in range(len(i[:2])):
if i[:2][c] not in dictionary.keys():
dictionary[i[:2][c]] = int(i[2:][c])
else:
dictionary[i[:2][c]] += int(i[2:][c])
print(dictionary)
In order to obtain the result of the opponent against a team, The below code satisfied the condition:
gameTab =[['TRE','ARD','1','1'],['PRK','GEA','2','3'],['ARD','PRK','1','0'],['TRE','GEA','2','1']]
dictionary = {}
for i in gameTab:
if i[0] in dictionary:
dictionary[i[0]] += int(i[3])
else:
dictionary[i[0]] = int(i[2])
if i[1] in dictionary:
dictionary[i[1]] += int(i[2])
else:
dictionary[i[1]] = int(i[2])
print(dictionary)
it prints out: {'ARD': 1, 'GEA': 4, 'TRE': 2, 'PRK': 3}
Basically traverse the list of lists, and for every team check if it exists in dictionary then increment its value as the opponents value. And finally you would get all point scored against a team by the opposition.
gametab = [['TRE','ARD','1','1'],['PRK','GEA','2','3'],['ARD','PRK','1','0'],['TRE','GEA','2','1']]
dicta = {}
for i in range(len(gametab)):
for j in range(2):
if gametab[i][j] in dicta:
dicta[gametab[i][j]] += int(gametab[i][j+2])
else:
dicta[gametab[i][j]] = int(gametab[i][j+2])
print dicta
I have a class of the form:
class data:
person.models.foreignKey("people.person")
place.models.foreignKey("places.place")
and I'm trying to create a dict containing places that have the same person associated with how many connections they have. IE:
dict={[place1:place2]:count}
so the dict might look like this:
dict={[place1:place2]:3, [place1:place3]:2, ect}
so far I have:
dict={}
datas=data.objects.all()
for data1 in datas:
for data2 in datas:
# if dict is empty
if not dict and data1.person == data2.person and data1.place != data2.place:
dict[(data1.place, data2.place)]=1
elif data1.person == data2.person and data1.place != data2.place:
for assoc, count in dict.items():
if assoc == (data1.place, data2.place) or assoc == (data2.place, data1.place):
count +=1
else:
dict[(data1.place, data2.place)]=1
else:
dict[(data1.place, data2.place)]=1
this is currently returning completely erroneous relations and never increments count. What am i doing wrong?
Do not use predefined names like dict for your variables. Think that your problem is that you try to increase count variable while you have to increase dict[key] - e.g. dict[key] += 1
dct = {}
datas = data.objects.all()
for data1 in datas:
for data2 in datas:
# if dict is empty
if not dct and data1.person == data2.person and data1.place != data2.place:
dct[(data1.place, data2.place)] = 1
elif data1.person == data2.person and data1.place != data2.place:
if (data1.place, data2.place) in dct:
dct[(data1.place, data2.place)] += 1
elif (data2.place, data1.place) in dct:
dct[(data2.place, data1.place)] += 1
else:
dct[(data1.place, data2.place)] = 1
else:
dct[(data1.place, data2.place)] = 1
Use annotations. I don't have you model layout, so this is an approximation of the logic. You'll need to tweak it to map to the correct stuff based on your implementation:
from django.db.models import Count
places = Place.objects.filter(people=thisguy).annotate(connections=Count('people'))
Then you can get the connections count via an attribute on each place:
places[0].connections