Dictionary
Dictionary
U23AD481
Course Description
• This course equips students with essential skills in Python programming
tailored for applications in Artificial Intelligence (AI).
• Through a combination of theoretical learning and hands-on practice, students
will gain proficiency in leveraging Python's capabilities to address real-world
challenges in various domains.
• The course covers fundamental concepts of Python programming, explores
• data structures, delves into object-oriented programming, and introduces
• scientific computing and Natural Language Processing (NLP) techniques.
Course Objectives
Output:
Dictionary with the use of dict():
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with keys and values
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output:
Dictionary with each item as a pair:
{1: 'Geeks', 2: 'For'}
Dictionary Items - Data Types
dict2 = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
print(dict2)
print(type(dict2)) { 'brand': 'Ford', 'electric': False, 'year': 1964, 'colors': ['red', 'white',
'blue']}
dict() Constructor
Output:
You can access the items of a dictionary by referring to its key name, inside
square brackets
dict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = dict["model"] #Get the value of the "model" key
Output: Mustang
Access Dictionary Items –get()
dict1 = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = dict1.get("model")
print(x) #Output: Mustang
Get Keys
• The keys() method will return a list of all the keys in the dictionary.
• The list of the keys is a view of the dictionary, meaning that any changes
done to the dictionary will be reflected in the keys list.
x = thisdict.keys()
Output: dict_keys(['brand', 'model', 'year'])
Get Values
The values() method will return a list of all the values in the dictionary.
The list of the values is a view of the dictionary, meaning that any changes done to the dictionary will be
reflected in the values list.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) # dict_values(['Ford', 'Mustang', 1964])
Add new key and value pair
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print("Before change:",car)
#Output: Before change: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
car["color"] = "white"
print("After Change:",car)
#Output: After Change: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'white'}
Get items
The items() method will return each item in a dictionary, as tuples in a list.
x = dict1.items()
print(x)
Output:
dict1_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
Check if Key Exists
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
# Yes, 'model' is one of the keys in the thisdict dictionary