Dictionary

  1. It consists of key value pairs.

  2. The value can be accessed by unique key in the dictionary.

Example - 1:

mydict = { 
    'name':'python',
    'build_year':1991,
    'Father of Python':"Guido Van Rossum",
    'Frame_works':['Django','Flask','Web2PY','Torando','kivi'],
    'versions' : [1.0,2.0,3.0],
    'latest_version':3.6}
    
print(mydict)
print("Name : ",mydict['name']) #returns the value of the key 'name'
print("Frame Works : ",mydict['Frame_works'])

{'name': 'python', 'buildyear': 1991, 'Father of Python': 'Guido Van Rossum', 'Frameworks': ['Django', 'Flask', 'Web2PY', 'Torando', 'kivi'], 'versions': [1.0, 2.0, 3.0], 'latestversion': 3.6}

Name : python

Frame Works : ['Django', 'Flask', 'Web2PY', 'Torando', 'kivi']

Example - 2:

k = mydict.get('versions')
print(k)
print(mydict.items())  #returns key value pair
print(mydict.keys())   #return keys
print(mydict.values()) #return values

[1.0, 2.0, 3.0]

dict_items([('name', 'python'), ('build_year', 1991), ('Father of Python', 'Guido Van Rossum'), ('Frame_works', ['Django', 'Flask', 'Web2PY', 'Torando', 'kivi']), ('versions', [1.0, 2.0, 3.0]), ('latest_version', 3.6)])

dict_keys(['name', 'build_year', 'Father of Python', 'Frame_works', 'versions', 'latest_version'])

dict_values(['python', 1991, 'Guido Van Rossum', ['Django', 'Flask', 'Web2PY', 'Torando', 'kivi'], [1.0, 2.0, 3.0], 3.6])

Example - 3:

mydict['scope']  = 'World Wide'   #add key 'scope'
mydict['name'] = "Python Programming Language"   #change value of key 'name' as key of this name already exist if it does not 
#then it will create key 'name'
print(mydict)

{'name': 'Python Programming Language', 'build_year': 1991, 'Father of Python': 'Guido Van Rossum', 'Frame_works': ['Django', 'Flask', 'Web2PY', 'Torando', 'kivi'], 'versions': [1.0, 2.0, 3.0], 'latest_version': 3.6, 'scope': 'World Wide'}

Example - 4:

dic = {"A":1, "B":2} 
print(dic["A"]) 
print(dic["C"]) 

KeyError Traceback (most recent call last)

in () 1 dic = {"A":1, "B":2} 2 print(dic["A"]) ----> 3 print(dic["C"])

KeyError: 'C' The get() method is used to avoid such situations. This method returns the value for the given key, if present in the dictionary. If not, then it will return None (if get() is used with only one argument).

The get() method is used to avoid such situations. This method returns the value for the given key, if present in the dictionary. If not, then it will return None (if get() is used with only one argument).

Example - 5:

dic = {"A":1, "B":2} 
print(dic.get("A")) 
print(dic.get("C")) 

1

None

Last updated