Dictionaries
'''
Dictionaries in Python:
In Python, dictionary is a built-in data type that stores data as key-value pairs.
They stores multiple items in a single variable.
They are separated by commas and enclosed within curly brackets{}.
They are ordered collection of data items.
Key Characteristics:
1. Ordered: Items do not have a defined order in Python versions < 3.7. In Python 3.7+, they maintain insertion order.
2. Mutable: We can change, add, or remove items.
3. Indexed by Keys: Each value is accessed using a unique key.
4. Keys Must Be Unique: Duplicate keys are not allowed.
Syntax:
dictionary_name = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
'''
#Example:
dic = {
"Sindhu": "Human Being",
"Lion" : "Animal",
"Parrot": "Bird"
}
print(dic["Sindhu"]) #output = Human Being
print(dic["Lion"]) #output = Animal
print(dic["Parrot"]) #output = Bird
info = {"Name": "Sindhu", "Age": 23, "Eligible": True}
print(info) #output = {'Name': 'Sindhu', 'Age': 23, 'Eligible': True}
'''
Accessing Dictionary Items:
1. Accessing Single Values:
Values in a dictionary can be accessed useing keys.
We can access dictionary values by mentioning keys either in square brackets or or by using get method.
2. Accessing Multiple Values:
We can print all the values in the dictionary by using values method().
'''
#Example1:
info = {"Name": "Sindhu", "Age": 23, "Eligible": True}
print(info) #output = {'Name': 'Sindhu', 'Age': 23, 'Eligible': True}
print(info["Name"]) #output = Sindhu
print(info.get("Name")) #output = Sindhu
#print(info["Name2"]) #output = KeyError: 'Name2'
#print(info.get("Name2")) #output = None
info = {"Name": "Sindhu", "Age": 23, "Eligible": True}
print(info.values()) #output = dict_values(['Sindhu'], 23, True)
print(info.keys()) #output = dict_keys(['Name', 'Age', 'Eligible'])
for key in info.keys():
print(info[key])
# #output = Sindhu
# 23
# True
for key in info.keys():
print(f"The value corresponding to the key {key} is {info[key]}")
# output = The value corresponding to the key Name is Sindhu
# The value corresponding to the key Age is 23
# The value corresponding to the key Eligible is True
'''
Accessing Keys:
We can access all the keys in the dictionary by using key() method.
'''
info = {"Name": "Sindhu", "Age": 23, "Eligible": True}
print(info.keys()) #output = dict_keys(['Name', 'Age', 'Eligible'])
'''
Accessing Key-Value Pairs:
We can print all the key-value pairs in the dictionary using items() method.
'''
info = {"Name": "Sindhu", "Age": 23, "Eligible": True}
print(info.items()) #output = dict_items([('Name' , 'Sindhu'),('Age' , 23), ('Eligible' , True)])
for key, value in info.items():
print(f"The value corresponding to the key {key} is {value}")
#output = The value corresponding to the key Name is Sindhu
# The value corresponding to the key Age is 23
# The value corresponding to the key Eligible is True
Comments
Post a Comment