Dictionaries

Dictionaries are used to store data values in key:value pairs. Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable.

Dictionaries are optimized to retrieve values when the key is known, which makes them better for use than lists in certain scenarios. Dictionaries in Python are implemented as hash tables under the hood, which allow you to look up whether an item exists in the table directly in constant run time instead of having to go through every element one at a time to check membership.

Creating a Dictionary


          # Initializing an empty dictionary
          dict1 = {}

          # Adding elements to a dictionary
          # Elements to the left of the : are known as keys
          # Elements to the right of the : are known as values

          stocks = {'AAPL' : 'Apple', 
                  'MSFT' : 'Microsoft',
                  'GOOG' : 'Google'}


          # Another example
          student = {'Name' : 'Faizan',
                   'Major' : 'Computer Science',
                   'Age' : 20}
                   

          # You can also create a dictionary of lists
          studentTestGrades = {'Faizan' : [90, 97, 85, 88],
                                'John' : [93, 87, 91, 94], 
                                'Mike' : [94, 88, 96, 86]}
          

         # You can also use the dict() function to create a dictionary 
         fruits = dict({1 : 'Apple', 2 : 'Orange', 3: 'Banana'})
        

Accessing Dictionary Items


          # Accessing an item with the key 

          student = {'Name' : 'Faizan',
                   'Major' : 'Computer Science',
                   'Age' : 20}
          
          name = student['Name']

          print(name)
          >>> Faizan

          age = student['Age']

          print(age)
          >>> 20


          studentTestGrades = {'Faizan' : [90, 97, 85, 88],
                               'John' : [93, 87, 91, 94], 
                               'Mike' : [94, 88, 96, 86]}
                        
          print(studentTestGrades['Faizan'])
          >>> [90, 97, 85, 88]


          # You can also use the get() function 

          car = {'brand': 'Tesla',
                 'model': 'Model X',
                 'year': 2021}
          
          model = car.get("model")
          
          print(model)
          >>> Model X


          # Accessing all dictionary keys

          keys = car.keys()

          print(list(keys))
          >>> ['brand', 'model', 'year']


          # Accessing all dictionary values

          values = car.values()

          print(list(values))
          >>> ['Tesla', 'Model X', 2021]


          # Accessing all dictionary items

          items = car.items()

          print(list(items))
          >>> [('brand', 'Tesla'), ('model', 'Model X'), ('year', 2021)]
        

Adding & Modifying Dictionary Items


          # Adding items to a dictionary

          address = {'street' : 123,
                     'avenue' : 85,
                     'city' : 'Lockwood'}

          print(address)
          >>> {'street': 123, 'avenue': 85, 'city': 'Lockwood'}

          address['state'] = 'New York'
          address['country'] = 'USA'

          print(address)
          >>> {'street': 123, 'avenue': 85, 'city': 'Lockwood', 'state': 'New York', 'country': 'USA'}


          # Modifying Dictionary Items

          address['city'] = 'Forest Hills'
          address['state'] = 'California'

          print(address)
          >>> {'street': 123, 'avenue': 85, 'city': 'Forest Hills', 'state': 'California', 'country': 'USA'}

        

Removing Dictionary Items


          # Removing items with the pop() function

          capitals = {'New York' : 'Albany',
                     'California' : 'Sacramento',
                     'Florida' : 'Tallahassee',
                     'Texas' : 'Austin'}

          # Remove Florida from the dictionary and return its value

          print(capitals.pop('Florida'))
          >>> Tallahassee

          # Florida is no longer in the dictionary
          print(capitals)
          >>> {'New York': 'Albany', 'California': 'Sacramento', 'Texas': 'Austin'}
          

          # Another example with the popitem() function
          
          stocks = {'AAPL' : 'Apple',
                    'MSFT' : 'Microsoft',
                    'GOOG' : 'Google'}

          # Remove the last item from of the dictionary and return it 
          # Returns the key : value pair

          print(stocks.popitem())
          >>> ('GOOG', 'Google')

          # Google is no longer in the dictionary

          print(stocks)
          >>> {'AAPL': 'Apple', 'MSFT': 'Microsoft'}


          # Remove all items from the dictionary

          stocks.clear()

          print(stocks)
          >>> {}
        

Checking Dictionary Membership


          # Simply use the keyword in to check if an item is in the dictionary

          stocks = {'AAPL' : 'Apple',
                    'MSFT' : 'Microsoft',
                    'GOOG' : 'Google'}

          print('AAPL' in stocks)
          >>> True

          # Use the values() function to check if a value is in the dictionary
          print('Microsoft' in stocks.values())
          >>> True


          print('FB' in stocks)
          >>> False

          print('NVDA' not in stocks):
          >>> True
        

Sorting Dictionaries


          # Utilize the sorted() and lambda functions to sort based on dictionary values
          
          studentGrades = {'John' : 90,
                            'Mike' : 92,
                            'James' : 85,
                            'Brian' : 88,
                            'Ken' : 95}

          sortedGrades = sorted(studentGrades.items(), key = lambda x : x[1], reverse = True)

          print(sortedGrades)
          >>> [('Ken', 95), ('Mike', 92), ('John', 90), ('Brian', 88), ('James', 85)]


          # The sorted() function can also be used to sort dictionary keys 
          # In this case, we will sort by alphabetical order
          
          students = {'Faizan' : 3.9, 
                      'Daniel' : 3.4,
                      'Alex' : 3.7, 
                      'Jake' : 3.6}

          sortedStudents = sorted(students.items())

          print(sortedStudents)
          >>> [('Alex', 3.7), ('Daniel', 3.4), ('Faizan', 3.9), ('Jake', 3.6)]

        

Iterating Over Dictionaries


          # Printing each key value pair
          
          capitals = {'New York' : 'Albany',
                     'California' : 'Sacramento',
                     'Florida' : 'Tallahassee',
                     'Texas' : 'Austin'}


          for key, value in capitals.items():
              print(key + ' -> ' + value)
          
          >>> New York -> Albany
              California -> Sacramento
              Florida -> Tallahassee
              Texas -> Austin
          

          # Another example

          studentTestGrades = {'Faizan' : [90, 97, 85, 88],
                               'John' : [93, 87, 91, 94], 
                               'Mike' : [94, 88, 96, 86]}

          for key, value in studentTestGrades.items():
              print(f"{key} : {value}")
          
          >>> Faizan : [90, 97, 85, 88]
              John : [93, 87, 91, 94]
              Mike : [94, 88, 96, 86]


          # Print every key

          for key in capitals:
              print(key)

          >>> New York
              California
              Florida
              Texas

          
          # Print every value 

          for value in capitals.values()
              print(value)
          
          >>> Albany
              Sacramento
              Tallahassee
              Austin
        

Dictionary Comprehension


          # Create dictionaries compactly in one line
          
          cities = ['New York', 'Tokyo', 'Paris']
          countries = ['USA', 'Japan', 'France']

          dict1 = {key: value for key, value in zip(cities, countries)}
          
          print(dict1)
          >>> {'New York': 'USA', 'Tokyo': 'Japan', 'Paris': 'France'}


          # Another example

          squares = {x: x*x for x in range(6)}

          print(squares)
          >>> {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}