Python dictionaries are easy 📙
ฝัง
- เผยแพร่เมื่อ 9 พ.ย. 2022
- #python #tutorial #course
dictionary = a collection of {key:value} pairs
ordered and changeable. No duplicates
capitals = {"USA": "Washington D.C.",
"India": "New Delhi",
"China": "Beijing",
"Russia": "Moscow"}
print(dir(capitals))
print(help(capitals))
print(capitals.get("Japan"))
if capitals.get("Russia"):
print("That capital exists")
else:
print("That capital doesn't exist")
capitals.update({"Germany": "Berlin"})
capitals.update({"USA": "Detroit"})
capitals.pop("China")
capitals.popitem()
capitals.clear()
keys = capitals.keys()
for key in capitals.keys():
print(key)
values = capitals.values()
for value in capitals.values():
print(value)
items = capitals.items()
for key, value in capitals.items():
print(f"{key}: {value}")
# dictionary = a collection of {key:value} pairs
# ordered and changeable. No duplicates
capitals = {"USA": "Washington D.C.",
"India": "New Delhi",
"China": "Beijing",
"Russia": "Moscow"}
# print(dir(capitals))
# print(help(capitals))
# print(capitals.get("Japan"))
# if capitals.get("Russia"):
# print("That capital exists")
# else:
# print("That capital doesn't exist")
# capitals.update({"Germany": "Berlin"})
# capitals.update({"USA": "Detroit"})
# capitals.pop("China")
# capitals.popitem()
# capitals.clear()
# keys = capitals.keys()
# for key in capitals.keys():
# print(key)
# values = capitals.values()
# for value in capitals.values():
# print(value)
# items = capitals.items()
# for key, value in capitals.items():
# print(f"{key}: {value}")
bro made the spaces perfectly :>)
This is the only course I can actually understand at this stage. Other courses say for "beginners"... well... maybe for someone else who is clever enough as a beginner to take those courses...
Nahhh, it's not you. I'm usually top of my class, and a lot of other "begginner" rated courses through TH-cam are taught by people who don't know how to teach effectively, or produce content that teaches rather than entertains. That, and a lot of others will also assume you know a lot of other things that are common to other programming languages.
I once saw a video labeled "for absolute beginners" and it was the most confusing thing I saw.
menu = {
"Burger": 40,
"Hotdog": 30,
"Pizza": 180,
"Chicken": 87
}
print("Menu:")
for item, price in menu.items():
print(f"{item} - {price}")
orders = []
while True:
item = input("What food would you like? ").capitalize()
if item.lower() == "done":
break
elif item not in menu:
print("Invalid item.")
continue
else:
quantity = int(input(f"How many {item}s do you want? "))
if quantity > 0:
orders.append((item, quantity))
print("You ordered:")
for order in orders:
print(f"{order[0]} x {order[1]}")
total = sum([menu[order[0]] * order[1] for order in orders])
print(f"The total amount of food is {total}pessos")
Thank you for explaining this topic so thoroughly and preemptively answerinf follow ups one may have. This is how teaching should be
You made this subject so interesting. Excellent teacher
One of the best explaination of python dictionaries
Thanks bro
2:27 Also, there is a second optional argument for the get() method where you can provide a value to return if the specified key does not exist. If you don’t give get() the second argument, you will just get `None` which is a special way of saying that there isn’t a value yet.
Definition 0:07
Example 0:20
.get method: 1:55
.update method 3:23
.keys method 4:55
.values method 5:58
Thx
4:20 china is destroyed*
Man, your teaching skills are so awesome. Thanks for helping us
This was very helpful. Thank you
You are legend
The best python tutor for me, I love your easy and fun teaching style❤
You seriously got a talent to teach
We certainly appreciate your efforts 😍
finally an explanation I understand completely and answered all of my issues, brilliant !!
You make it so easy
For those people who are greedy with their self but you the are who really help us so many are privileged and innocent people's are here those who don't have money or own laptop these type people's are also here a huge respect to you brother 😢 you are helping us you are the teacher of us - thanks to you bro 💖
Thank you!
This video was soooooo helpfull
great video ! helped a lot
Thank you so much
Dope content.
helps remembering after reading a book. tysm!
Yeah this actually helped alot
your voice is smooth and attractive i could see you working as a narrator
This is great
god bless this
Very clear
You're awesome, bro! 😎
yep
Thanks g
Very good bro! You’ve just earn a subscriber
Thanks big bro
Hello, thanks for the helpful video! I have a question, you kept mentioning something along the lines of "it returns an object resembling a list" but also as you both stated and demonstrated this object is iterable. Are there situations where the difference will matter?
Great video as alwys. For me especially the dir() and help(). I didn't know they existed. What would a dictonairy mostly be used for and how?
thanks bro
Mast h dekh watch this video from India 🇮🇳🥰
Bro you are great programer 😊
I love you Bro Code
I'm creating a command line rpg level up on python, I use a list for a lot of stuff especially on the saving mechanics, should I use dictionary instead? can I use dictionaries for hp and energy?
thank you Bro Code
quick question: i also get the value if i just use dict[key] like capitals["USA"]. What is the benefit of using the get method?. ok just figured out the benefit of the get method. it returns none instead of throwing a key error.
but whats the benefit of dict.update?
I can just use capitals["France"] = "Paris"
Holy crap that dir function
Bro, superb instructions of dictionaries and advance topics for dummies. Love how you teach, suscribed--bell rung, I'll be back. Thank you!
I thought that dicts arent ordered because i cannot use position idexes to get some pair, key or value?
godlike
as a person who has an exam tommorow about this, thank you
4:17 That was brutallll...!!😂
Duck yes bro! Duck yes! 🙌
Gigachad.
thank you good sir , tomorrow is my exam and i shall be passing thanks to you.
what can i say ? it was really easy , a like from me
hello, please tell me how to make my display on the editor look like yours
But most of the resources says that dictionary is unordered
when i type in all small letter, it says it doesnt exist. how can i change it, thanks
This title is kinda pretencious right now, but in a few years you and many computer science communicators will make it gain worth. I appreciate your labor here, shall many enthusiastics like me come to your channel and get their doubts cleared up the same way mines did just tonight. Regards from venezuela
will you do a golang tutorial?
Giga chad
ye
"No thats herp"
We definitely don't want that 👀
are dictionaries similar to hashmaps?
yup, they are basically the same thing, named differently because theyre from different languages
Me watching this video for my semester finals that gonna be happen in 2 more hours
Why does popitem(last item) work if a dict is unordered?
It’s not unordered though. It will remove and return the last key-value pair that was inserted.
Thanks for your video! can you help me I'm stupid? you don't have to dive into the code the 2nd to last line will print the dictionary so you can see it works It's just the last line that doesn't work like yours does? Ive tried double quotes, single, I've tried making with all strings and a digit/string. You can just run it and see the dictionary creates and is there, BUT why doesnt the last line work??
i = 21 # 21 is first key on left side of piano low A
i = int(i) # i is an integer
x = 21 + 88 # 109 is last key on right
y = 0 # y is the index number of each of the 12 notes starting from A moving right
o = 0 # o is index of octave so it start at - "A0", "A#0/Bb0" ..... "A1", "A#1/Bb1 ... etc..."
y = int(y)
notes = ["A", "A#/Bb", "B", "C", "C#/Db", "D", "D#/Eb", "E", "F","F#/Gb", "G","G#/Ab"]
while i < x:
notename = (notes[y])
oct = str(o)
cnct =(notename) + (oct) #concatenate notename and octave as string
istr = str(i)
numNote = {istr: cnct} # create first dictionary number is the key, note name is value
noteNum = {cnct: istr} # create second dictionary reversed
y = y + 1
if y == 12: #after you go thru the 12 notes
y = 0 #set y back to 0 and start the next 12 notes
o = o + 1 #after the first 12 notes advance the octave 1
i = i + 1 #iterate thru keys 21 - 109
print(numNote)
print(numNote.get("102"))
It was a bit difficult but I have just solved it:
i = 21 # 21 is first key on left side of piano low A
x = i + 88 # 109 is last key on right
y = 0 # y is the index number of each of the 12 notes starting from A moving right
notes = ["A", "A#/Bb", "B", "C", "C#/Db", "D", "D#/Eb", "E", "F","F#/Gb", "G","G#/Ab"]
a1_dict = {}
while i x:
break
else:
pass
print(a1_dict)
I see that your program creates a dictionary for every single pair of key : note, and I consider it unnecesarry, since dictionaries can hold a lot of key : note pairs.
3:30
BroCode, i come frequently and see the dir() function because i forget the name of the dir() function😂😂
ay i was the 5000th like on this does that mean ill pass the exam tmrw
Almost typed herpes there
Trying to let my dumbo mind work with coding. Its tough!
How login and password work in website. Please help me about it😢
It works using html. Password is an input type in html. See a good video about login pages 😃
I could have helped but you need a good teacher
bonsoir hugo...
j'en suis ravis
ok
I am from Russia.
Nice! happy learning
@@skingleyjoseph5402 Thanks, I made a cool calculator by a video, it is gonna be so cool!
A terrorist left here!
thx bro i love you
Indian with an american accent
I get that lol
I have my cs exam soon Im just re watching all your vids cause my professor useless af.
hugo, répond à ce commentaire veux tu!
j'y comprend plus rien moi
In this exercise, you are asked to fill in the function top_grade(). • This function receives a list of dictionaries. All the dictionaries in the list will have the same keys - “name” and “grades”.
• We want to know, for each student, what is their best grade and in which subject.
• So, the function should return a new list with the same number of dictionaries as the original.
• However, instead of the “grades” key, it should have the “best grade” key, whose value should be a dictionary with the key being the subject name and its value the maximum value of the “grades” key on the original dictionary.
See the example below:
example = [{'name': 'John', 'grades': {'Math': 80, 'Algebra': 76, 'Economics': 82}}, {'name': 'Max', 'grades': {'Math': 85, 'Algebra': 90, 'Economics': 88}}, {'name': 'Zygmund', 'grades': {'Math': 80, 'Algebra': 76, 'Economics': 82}}]
top_grade(example) [{'name': 'John', 'best grade': {'Economics': 82}}, {'name': 'Max', 'best grade': {'Algebra': 90}},
{'name': 'Zygmund', 'best grade': {'Economics': 82}}]
@@user-nc1qz4ku9n def top_grade(students):
top_grades = []
for student in students:
name = student['name']
grades = student['grades']
best_subject = max(grades, key=grades.get)
best_grade = grades[best_subject]
top_grades.append({'name': name, 'best grade': {best_subject: best_grade}})
return top_grades
@@couz-kv2ri Complete the custom_operator() function, which takes a list of integer numbers as input. The
function should return a new list of the same length, following these rules:
The first and last numbers in the output list should be double the original values.
For the remaining numbers in the output list, calculate each value by multiplying the original
list of numbers (excluding the number at the current index) by the number at the current
index, and then summing all the results.
Here's an example to illustrate the desired transformation:
Example:
[1,2,3,4,5,6,7]
Output:
[2, 52, 75, 96, 115, 132, 14]
@@ludovikthorens4743 j'ai changé, plus visuel comme ça :
def custom_operator(lst):
n = len(lst)
if n == 0:
return lst
res = [0]*n
# Double the first and last elements
res[0], res[-1] = 2*lst[0], 2*lst[-1]
# Compute the result for the remaining elements
for i in range(1, n-1):
sum_val = 0
for j in range(n):
if j != i:
sum_val += lst[j]*lst[i]
res[i] = sum_val
return res
how come during the section @3:09 you type "Japan" into the parameter and get a true//false result? I would expect that typing in "Japan" there would mean that "Japan" would become the desired argument for the if/else statement.
Thanks Bro hopefully gonna go get a C on my quiz instead of a D 🫡
Thanks, bro. You really helped me