Skip to content

Instantly share code, notes, and snippets.

@wildonion
Created October 28, 2020 11:48
Show Gist options
  • Save wildonion/26500b3f0b9de6cc501dbda5a08f38a8 to your computer and use it in GitHub Desktop.
Save wildonion/26500b3f0b9de6cc501dbda5a08f38a8 to your computer and use it in GitHub Desktop.
python dictionary example
# >>> d={"adventurous":"aventurero","bold":"audaz","courageous":"valiente"}
# >>>d.items()
# [('courageous', 'valiente'), ('adventurous', 'aventurero'), ('bold', 'audaz')]
# >>> d.keys()
# ['courageous', 'adventurous', 'bold']
# >>> d.values()
# ['valiente', 'aventurero', 'audaz']
# >>> my_list = [('a', 1), ('b', 2)]
# >>> dict(my_list)
# {'a': 1, 'b': 2}
# TODO: runtime and time complexity issue!!! make the code simple!
def makelst(A):
avglist = []
for key in A.keys():
avglist.append(float(A[key]["avg"]))
return avglist
def sortavglst(avglist):
n = len(avglist)
for i in range(n):
for j in range(0, n-i-1):
if avglist[j] > avglist[j+1] :
avglist[j], avglist[j+1] = avglist[j+1], avglist[j]
return avglist
def createRATE(avgsortedlst, A):
for key in A.keys():
for i in range(len(avgsortedlst)):
if A[key]["avg"] == avgsortedlst[i]:
A[key]["rate"] = i+1
def calAVG(A):
for key in A.keys():
s = 0
for i in A[key]["course_info"]:
s+= float(i[1])
avg = s/len(A[key]["course_info"])
A[key]["avg"] = avg
def fillMe():
A = {}
for i in range(int(input("[+] REGISTERING FOR ? >>> "))):
A[int(input("[+] STU ID >>> "))] = {"name": str(input("[+] NAME >>> ")),
"lname": str(input("[+] LASTNAME >>> ")),
"avg": None,
"rate": None,
"course_info": [tuple(input("[+] WRITE COURSE NAME->MARK >>> ").split("->")) for cname in range(int(input("[+] COURSE NUMBER ? >>> ")))]
}
return A
def printMe(A):
print("\n\n")
for key in A.keys():
print("STUID =========\n")
print("{}\n".format(A[key]))
print("FIRSTNAME ========\n")
print("{}\n".format(A[key]["name"]))
print("LASTNAME ========\n")
print("{}\n".format(A[key]["lname"]))
print("AVERAGE ========\n")
print("{}\n".format(A[key]["avg"]))
print("RATE ========\n")
print("{}\n".format(A[key]["rate"]))
print("COURSE INFO =========\n")
for i in A[key]["course_info"]:
print("{} -> {}".format(i[0], i[1]))
print("\n")
if __name__ =="__main__":
A = fillMe()
calAVG(A)
createRATE(sortavglst(makelst(A)), A)
printMe(A)
# =====================================
# multi same dict key and their values
# METHOD 1
class Dictlist(dict):
def __setitem__(self, key, value):
try:
self[key]
except KeyError:
super(Dictlist, self).__setitem__(key, [])
self[key].append(value)
d = dictlist.Dictlist()
d['test'] = 1
d['test'] = 2
d['test'] = 3
# >>> d
# {'test': [1, 2, 3]}
d['other'] = 100
# >>> d
# {'test': [1, 2, 3], 'other': [100]}
# METHOD 2
class DictList(dict):
def __setitem__(self, key, value):
try:
# Assumes there is a list on the key
self[key].append(value)
except KeyError: # if fails because there is no key
super(DictList, self).__setitem__(key, value)
except AttributeError: # if fails because it is not a list
super(DictList, self).__setitem__(key, [self[key], value])
dl = DictList()
dl['a'] = 1
dl['b'] = 2
dl['b'] = 3
# OUTPUT: {'a': 1, 'b': [2, 3]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment