Python Dictionaries

Python Dictionaries are used to store data as Key:Value. They’re changeable, unordered (In Python 3.6 and earlier) that let you store information in a way where each piece of data is linked to a distinct identifier (key:value pair). Python dictionary key and value are very important and useful in term of identification element in dictionary. You can create a dictionary using curly braces {} and separating key-value pairs with colons :. They are different from Python Tuples and Sets in kind of storing data, while both Sets and Tuples are not required key:value as pairs to access data. The overview Python dictionary examples below:

Python dictionary examples:

We can create empty dictionary with the only curly braces.

myCar={};

The example shows how to store data in dictionary with keys and value. Keys are ‘Brands’, ‘Model’, & ‘Year’ that pairs the values of ‘Lexus’,’ LX300′, & ‘2024’.

#Syntax: myCar={'Keys':'Value'}
myCar={'Brands':'Lexus',
       'Model':'LX300',
       'Year:':'2024' }
print(myCar)
#output: {'Brands': 'Lexus', 'Model': 'LX300', 'Year:': '2024'}
Accessing Item by Keys

We can simply use square brackets [] with the key inside to access item in Python Dictionary. This code demonstrates that accessing items in the myCar dictionary by keys such as (“Brands”, “Model”, and “Year”). When using myCar["Brands"], it returns the value associated with the key “Brands” in the dictionary, which its value is “Lexus”. See code below:

myCar={'Brands':'Lexus',
       'Model':'LX300',
       'Year:':'2024' }
print(myCar['Brands'])
#output: Lexus
Dictionary Item with data type

In Python dictionaries, the values associated with keys can be of any data type, including built-in types like integers, floats, strings, lists, tuples, sets, and even other dictionaries. Here the example below:

myDict = {
    "Name": "Sophy",
    "Age": 37,
    "Gender":"Female",
    "Is_student": True,
    "Grades": [80, 90, 92],
    "Coordinates": (31.71, -55.00),
    "Address": {
        "street": "16 Cabramatta RD",
        "city": "Cabrammtta",
        "zipcode": "2166"
    }
}
print(myDict["Name"])
print(myDict["Age"])
print(myDict["Gender"])
print(myDict["Is_student"])
print(myDict["Grades"])
print(myDict["Coordinates"])
print(myDict["Address"])

#output: 

# Sophy
# 37
# Female
# True
# [80, 90, 92]
# (31.71, -55.0)
# {'street': '16 Cabramatta RD', 'city': 'Cabrammtta', 'zipcode': '2166'

In the example above shows that:

  • “Name”, “Age”,”Gender”: its value are string and integer data type.
  • “Is_student” : its value is Boolean data type.
  • “Grades”: its value is also integer.
  • “Coordicates”: its value is a tuple containing latitude and longitude.
  • “Address”: its value is a bench of dictionary which containing address details.
Python Dictionary Dict()

The dict() constructor in Python is a built-in function used to create dictionaries. It can take different types of arguments and return a new dictionary based on those arguments.

For example:

# Create an empty dictionary
empDict = dict()

# Create a dictionary with keyword arguments
arg_dict = dict(name="Sophy", age=37, city="Sydney")

# Create a dictionary from another dictionary
myDict = {"aa": 1, "bb": 2, "cc": 3}
myDict_copy = dict(myDict)

print("Empty Dictionary:", empDict)
print("Dictionary from Iterable:", arg_dict)
print("Another Dictionary:", myDict_copy)

#output:

#Empty Dictionary: {}
#Dictionary from Iterable: {'name': 'Sophy', 'age': 37, 'city': 'Sydney'}
#Another Dictionary: {'aa': 1, 'bb': 2, 'cc': 3}

The dict() constructor offers versatility in generating dictionaries from diverse inputs, simplifying its use across a range of programming contexts.

freecode4learn.com

Leave a Reply