Python Dictionary – A quick reference


  1. Built-in data structure, Mutable
  2. Unordered collection of items in the form of a key: value pair
  3. Aabhar : https://allinpython.com/explain-python-dictionary-in-detail/
# Create dictionary using {} or dict
myEmptyOrInitializableDict = {}
print(type(myEmptyOrInitializableDict) , " --- ", myEmptyOrInitializableDict)
# RESULT -> <class 'dict'>  ---  {}

myInitializedDict = {'PythonDesignedBy' : 'Van Rossum' }
print(type(myInitializedDict), "---", myInitializedDict)
# RESULT -> <class 'dict'> --- {'PythonDesignedBy': 'Van Rossum'}

myDict = dict(language='Python', usage='Scientific', rating=5)
#myDict2 = dict('language'='PHP', 'usage'='Web Development') # SyntaxError as keys are made of quoted
print(myDict)
# RESULT -> {'language': 'Python', 'usage': 'Scientific', 'rating': 5}

print(type(myDict.keys()), " ----", myDict.keys())
print(type(myDict.values()), " ----" , myDict.values())
print('language' in myDict) # Check if key is present
print('PHP' in myDict.values()) # Check if value is present
# RESULT -> <class 'dict_keys'>  ---- dict_keys(['language', 'usage', 'rating'])
# RESULT -> <class 'dict_values'>  ---- dict_values(['Python', 'Scientific', 5])
# RESULT -> True
# RESULT -> False

#Traversing a dictionary
for key in myDict:    
    print(key , "->" , myDict['language'])
    
""" RESULT -> 
language -> Python
usage -> Python
rating -> Python
"""    

#Major Methods 
print( myDict.get('rating') )
print(myDict.pop('rating') , " -- After Pop myDict is -- ", myDict)
print(myDict.popitem(), " -- After popitem myDict is --", myDict) # removes the last most item
#RESULT -> 5
#RESULT -> 5  -- After Pop myDict is --  {'language': 'Python', 'usage': 'Scientific'}
#RESULT -> ('usage', 'Scientific')  -- After popitem myDict is -- {'language': 'Python'}

myDict.update({'popularity' : 'High'})
myDict.update(dict(usage = 'Univeral'))
print(myDict)
#RESULT -> {'language': 'Python', 'popularity': 'High', 'usage': 'Univeral'}

myDictCopy = myDict.copy();
print(myDictCopy);
#RESULT -> {'language': 'Python', 'popularity': 'High', 'usage': 'Univeral'}

myDictCopy.clear()
print(myDictCopy) 
#RESULT -> {}
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s