Dictionaries

Dictionaries are collections of key-value pairs. Each key in a dictionary is unique and maps to a value. Dictionaries are created using curly braces {} or the dict() function.

# Creating a dictionary of names and ages
my_dict = {"Alice": 25, "Bob": 30, "Charlie": 35}

# Creating a dictionary of stock prices
stock_prices = {"AAPL": 135.39, "GOOG": 2066.76, "MSFT": 231.60, "AMZN": 3113.59}

In this dictionary, each key is a stock ticker symbol (e.g. “AAPL” for Apple) and each value is the current stock price for that company. You could access the stock price for a particular company like this:

print(stock_prices["AAPL"])

This would output “135.39”, which is the current stock price for Apple. You could also add new stock prices to the dictionary like this:

stock_prices["TSLA"] = 597.95

And you could remove a stock price like this:

del stock_prices["MSFT"]

 

Learn Python :https://learndataengineeringskills.com/category/python/

Leave a Comment