Dictionaries in Python
Using dictionaries with a bunch of key value pairs,
These are key value pairs
Name = test
Email = test@gmail.com
Phone = 23433
Will see now how to define and use dictionary in Python
Keys would be unique on dictionary
customer = {
"name": "krish",
"age": 22,
"is_verified": True
}
print(customer["name"])
output:
krish
if we pass the name which is not available in dictionary which will returns key error
and also we can use get method to get the key value pairs
print(customer.get("name"))
in this scenario if the key is not available it would be print None says that object is not available.
Updating the dictionary values as well
customer = {
"name": "krish",
"age": 22,
"is_verified": True
}
customer["name"] = "John"
print(customer["name"])
also add new key value pairs here like
customer["email"] = "john@mail.com"
print(customer["email"])
Exercise:
Print 1234 users phone number in words for an example
phone = input("Phone: ")
mapping = {
"1": "One",
"2": "Two",
"3": "Three",
"4": "Four"
}
output = ""
for ch in phone:
output += mapping.get(ch, "!") + " "
print(output)
output:
Phone: 1235
One Two Three !