Menu

Tuples, Sets, and Dictionaries

Tuples, Sets, and Dictionaries

Python provides several data structures, each designed for different requirements.

Tuples for Fixed Collections

Tuples are ordered collections that cannot be modified after creation. They are useful for grouping related values that should remain unchanged.

product = ("Laptop", 55000, "Electronics")
name = product[0]
price = product[1]
print(name)
print(price)

A tuple can hold values of different data types, making it suitable for representing a simple record.

Sets for Unique Values

Sets store unique elements and are useful for identifying distinct categories or removing duplicates.

customer_cities = [

"Chennai", "Delhi", "Chennai",

"Mumbai", "Delhi", "Pune"

]

unique_cities = set(customer_cities)

print(unique_cities)

print("Unique cities:", len(unique_cities))

Sets do not guarantee a particular display order. If you need sorted output, use sorted().

print(sorted(unique_cities))

Dictionaries for Key-Value Data

Dictionaries store information as key-value pairs. They are useful for representing records and looking up values by meaningful names.

product = {

"name": "Laptop",

"price": 55000,

"rating": 4.5

}

print(product["name"])

print(product["price"])

You can add or update values using their keys.

product["stock"] = 25

product["price"] = 53000

print(product)

Dictionaries are particularly useful when working with JSON data returned by APIs or representing individual records before loading them into a Pandas DataFrame.


Python for Data Science

VA

Vishalini A



Learn via Video Course

undefined Logo

NaN hrs



Get in Touch For Details