Dictionary
• a dictionary is a collection that allows us to store
data in key-value pairs.
• Note: Dictionary keys must be immutable, such as
tuples, strings, integers, etc. We cannot change
objects such as lists as keys.
• Create a Dictionary
– create dictionaries by placing key:value pairs inside
curly brackets {}, separated by commas.
– Eg :
• # creating a dictionary
• cc = {
• "United States": "Washington D.C.",
• "Italy": "Rome",
• "England": "London"
• }
• print(cc)
• Dictionary Length
• We can get the size of a dictionary by using
the len() function.
– print (len(cc))
• Access Dictionary Items
– To access the value of a dictionary item by placing the key inside
square brackets.
– get() method : this function returns the value of the given key. If
the key does not exist I the dictionary, it return None.
– Eg :
• scores = {
• 'Physics': 67,
• 'Maths': 87,
• 'History': 75
• }
• result = scores.get('Physics')
• result
• #print(scores) # 67
• Eg :
– # if key ot present it reurn NONE
– d={1:'1',2:'22',3:'333',4:'4444',5:'5555'}
– x=d.get(3)
– print(x)
– y=d.get(9)
– print(y,"Does Not Exists")
• Keys() : this methods returns all the keys of the dictionary.
• Eg :
– # to display only keys
– d={1:'1',2:'22',3:'333',4:'4444',5:'5555'}
– a=d.keys()
– print(a)
• Items() : this method returns all the items in the dictionary as a
sequence of (key,value) tuples.
• Eg :
– # to display items
– d={1:'1',2:'22',3:'333',4:'4444',5:'5555'}
– a=d.items()
– print(a)
• Values () : this method returns all the values from the dictionary.
• Eg :
– # to display dictionary value
– d={1:'1',2:'22',3:'333',4:'4444',5:'5555'}
– a=d.values()
– print(a)
• Formkeys() : this method is used to create a new dictionary from a sequence(list,
set, tuple, string) containing all the keys and a common value which will be assigned
to all the keys.
• Syntax : dict.formkeys(<key sequence>,[<value>])
• Value: it is common value assigned to all the keys, if skipped, value None is assigned
to all the keys.
• Eg :
– d1=dict.fromkeys('swati',12)
– print(d1)
– d1=dict.fromkeys([1,2,3,4],200),
– print(d1)
– #multiples values assign to keys
– d1=dict.fromkeys((1,2,3,4,5),(10,20,30,40,50))
– print(d1)
– #also assign keys to values in the dictionary also
– d1=dict.fromkeys({1:12,2:'hello',3:'msi'},100)
– print(d1)
• Setdefault() : if the given key is not already present in
the dictionary, it will add the specified new key:value
pair to the dictionary and return the value of the
added key.
• Eg :
– ## setdefault function
– marks={1:350,2:450,3:450,4:550,5:650}
– marks.setdefault(6,'msi')
– print(marks)
• If the given key is already present in the dictionary,
then the existing value of that key will not be updated.
• Eg :
– ## setdefault function
– marks={1:350,2:450,3:450,4:550,5:650}
– marks.setdefault(3,'msi')
– print(marks)
• If you only provide key without any value and the key
doesn’t exist in the dictionary, it will return as its value.
• Eg :
– ## setdefault function return NONE
– marks={1:350,2:450,3:450,4:550,5:650}
– marks.setdefault(6)
– print(marks)
• Pop() : this method removes and returns the dictionary
element associated to passed key.
• Syntax : dict.pop(key,<msg>)
• Msg: the message will be displayed if the given key is not
found in the dictionary. If you skip this value and the given
key is not found, the it will generate the error.
• Eg :
– ## pop
– d={1:350,2:450,3:450,4:550,5:650}
– d.pop(7,'keynotavailable')
– print(d)
• Sorted() : this method considers only the keys of the
dictionary for sorting and returns the sorted list of the
dictionary keys.
• Syntax: sorted(dict,[reverse=false])
• Eg :
– ## sorted by keys
– s = {41:'name',6: 'John',9: 'age', 27:'sex',8: 'Male'}
– s1=sorted(s)
– print(s1)
• Eg : sorted by values
– ## sorted by values
– s = {41:'name',6: 'john',9: 'age', 27:'sex',8: 'male'}
– s1=sorted(dict.values(s))
– print(s1)
• Change Dictionary Items
– Python dictionaries are mutable (changeable). We can change the value of a
dictionary element by referring to its key.
– Eg :
• scores = {
• 'Physics': 67,
• 'Maths': 87,
• 'History': 75
• }
• #change the value
• res=scores["math"]=100
• Res
• Add Items to a Dictionary
– We can add an item to the dictionary by assigning a value to a new key (that
does not exist in the dictionary).
– Eg :
• scores = {
• 'Physics': 67,
• 'Maths': 87,
• 'History': 75,
• 'Istsem':{'fit':98,'WT':94,'C':98}
• }
• #add new value
• scores["physics"]=95
• scores
• Remove Dictionary Items
– We use the del statement to remove an element from the dictionary.
– Eg :
• scores = {
• 'Physics': 67,
• 'Maths': 87,
• 'History': 75,
• 'Istsem':{'fit':98,'WT':94,'C':98}
• }
• #delete value
• del scores['Maths']
• Scores
• If we need to remove all items from the dictionary at once, we can use
the clear() method.
• Eg :
– scores = {
– 'Physics': 67,
– 'Maths': 87,
– 'History': 75,
– 'Istsem':{'fit':98,'WT':94,'C':98}
– }
– #clear all value
– scores.clear()
– scores
• Copy : this method returns a copy of the specified
dictionary.
• Eg :
– car = {
– "brand": "Ford",
– "model": "Mustang",
– "year": 1964
– }
– car1 = car.copy()
– print(car1)
• Note : #now if iu want to delete some items from copy
dictionary
• #then original dictionary items will not deleted but
• #if we simply assign the dictionary to any another var
• # then original dic items delete
• ## to print only keys
• Eg :
– car = {
– "brand": "Ford",
– "model": "Mustang",
– "year": 1964
– }
– print (car.keys())
– # to print dic items
– print (car.items())
• Iterating Through a Dictionary
– A dictionary is an ordered collection of items. We can iterate
through dictionary keys one by one using a for loop.
– country_capitals = {
– "United States": "Washington D.C.",
– "Italy": "Naples"
– }
– # print dictionary keys one by one
– for country in country_capitals:
– print(country)
– print("----------")
– # print dictionary values one by one
– for country in country_capitals:
– capital = country_capitals[country]
– print(capital)
Nested Dictionary
• a nested dictionary is a dictionary inside a
dictionary. It's a collection of dictionaries into one
single dictionary. It has two dictionary each having
own key and value.
• Create a Nested Dictionary
• Eg :
– ## to create nested dictionary
– people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
– 2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
– print(people)
• Access elements of a Nested Dictionary
– To access the element of a nested dictionary, we use indexing.
– Eg :
• # access element
• people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
• 2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
• print(people[1]['name'])
• print(people[1]['age'])
• print(people[2]['sex'])
• Add element to a Nested Dictionary
– to add values one by one or whole dictionary in one go.
– Eg :
– people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
– 2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
– people[3] = {}
– people[3]['name'] = 'Luna'
– people[3]['age'] = '24'
– people[3]['sex'] = 'Female'
– people[3]['married'] = 'No'
– print(people[3])
– # Adding whole dictionary
– people['4'] = {'name': 'Harry', 'age': 25,'married':'yes'}
– print("\nAfter adding dictionary Dict1")
– print(people)
• Delete elements from a Nested Dictionary
– we use “ del “ statement to delete elements from nested dictionary.
• ## delete items from nested dic
• people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
• 2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
• 3: {'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'},
• 4: {'name': 'Peter', 'age': '29', 'sex': 'Male', 'married': 'Yes'}}
• del people[3]['married']
• del people[4]['sex']
• print(people[3])
• print(people[4])
to delete dictionary from a nested
dictionary
• ## to delete dictionary from a nested dictionary?
• people = {1: {'name': 'John', 'age': '27', 'sex':
'Male'},
• 2: {'name': 'Marie', 'age': '22', 'sex':
'Female'},
• 3: {'name': 'Luna', 'age': '24', 'sex': 'Female'},
• 4: {'name': 'Peter', 'age': '29', 'sex': 'Male'}}
• del people[3], people[4]
• print(people)
• Iterating Through a Nested Dictionary
– Using the for loops, we can iterate through each elements
in a nested dictionary.
– Eg :
• ## through loops
• people = {1: {'Name': 'John', 'Age': '27', 'Sex': 'Male'},
• 2: {'Name': 'Marie', 'Age': '22', 'Sex': 'Female'}}
• for p_id, p_info in people.items():
• print("\nPerson ID:", p_id)
•
• for key in p_info:
• print(key + ':', p_info[key])
• to Merge two nested dictionaries?
– Merging two nested dictionaries using the update() method.
– Eg :
– # to merge to dictionaries
– c1={"1":{"Country": "India",
– "Capital": "Dehli",
– "Population": "1,414,681,270"},
– "2":{"Country": "United State",
– "Capital": "Washington, D.C.",
– "Population": "335,962,130"}}
– c2={"3":{"Country": "China",
– "Capital": "Beijing",
– "Population": "1,453,523,041"},
– "4":{"Country": "Russia",
– "Capital": "Moscow",
– "Population": "146,098,876"}
– }
– c3=c1.update(c2)
– # n this, the second list is merged into the first list and
– #no new list is created. It returns None.
– print(c3)
– print(c1)