Python Dictionary
Python Dictionary
● Dictionary holds key:value pair which are separated by comma and enclosed
● Value: it belongs to any data type like as number, string, Boolean, list,
One value at a time can be added to a Dictionary by defining value along with the key
dict[2]=”roshan”
print(dict)
get() that will also help in accessing the element from a dictionary.
Syntax : dict_name.get(key)
Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
print("Accessing a element using get:")
print(Dict.get(3))
output: Geeks
Accessing an element of a nested dictionary
In order to access the value of any key in the nested dictionary, use indexing []
syntax.
Creating a Dictionary
print(Dict['Dict1'])
print(Dict['Dict1'][1])
print(Dict['Dict2']['Name'])
output: {1: 'Geeks'}
Geeks
For
Deleting Elements using del Keyword
The items of the dictionary can be deleted by using the del keyword as given below.
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
print(Dict)
del(Dict[1])
print(Dict)
Output {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
{'name': 'For', 3: 'Geeks'}
dictionary methods
1. clear() - Remove all the elements from the dictionary
dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}
print(dict1.clear)
output: {}
print(d)
d1 = {3: "three"}
print(d)
{1: 'one', 2: 'two'}
The pop() method removes the specified item from the dictionary.
car = {“brand": "Ford", “model": "Mustang", "year": 1964}
car.pop("model")
print(car)
output: {“brand": "Ford", "year": 1964}