Home Backend Development Python Tutorial Python - Dictionary, Set, Tuple

Python - Dictionary, Set, Tuple

Aug 12, 2024 pm 10:35 PM

All three are different type of data structures in python. This is used to store different Collections of data. Based on the usecase of our requirement, we need to choose among these.

Python - Dictionary, Set, Tuple

Dictionary (dict):

  1. Dictionary is collection of key value pair, where each key is associated with a value
  2. Data can be retrieved based on key value(Key based search) as the keys are required to be unique.
  3. Dictionaries are unordered till 3.7, values can be changed. Key name cannot be changed directly

Syntax:
inventory = {'apple':20, 'Banana':30 , 'carrot':15, 'milk':15}
print('t1. Inventory items', inventory)

Dictionaries can be added with another value/modfied the value of existing key using the below syntax

inventory['egg'] = 20
inventory['bread'] = 25
print('t2. Updated Inventory items', inventory)
inventory['egg']= inventory['egg']+5
print('t3. After restocking', inventory)

  • removing the data from dict can be done using del keyword.
  • Checking the presence of data can be done using in keyword. Result will be boolean.

del inventory['carrot']
del inventory['bread']
print('t4. Updated Inventory after delete', inventory)

is_bananas_in_inventory = 'Banana' in inventory
print('t5a. Is banana in inventory', is_bananas_in_inventory)
is_oranges_in_inventory = 'Orange' in inventory
print('t5b. Is Orange in inventory', is_oranges_in_inventory)

Notes:
Additionaly dict.items() will give each item in dictionary as tuple (like key value pair). by using list(dict.items()) we can also get the data as list. Using for loop and if condition, we can access particular key and do the desired operation for that data

for product, product_count in inventory.items():
    print('\t\t6. Product:', product, 'count is:', product_count)
print ('\t7. Iterating inventory gives tuple:', inventory.items())

#Printing only egg count(Value of key 'egg') by itearting dict
for product, product_count in inventory.items():
    if product is 'egg':
        print('\t8. Product:', product, ' its count is:', product_count)

#Printing egg count (value of key 'egg')
print('\t9. Count of apple',inventory['egg'])
Copy after login
Output:
        1. Inventory items {'apple': 20, 'Banana': 30, 'carrot': 15, 'milk': 15}
        2. Updated Inventory items {'apple': 20, 'Banana': 30, 'carrot': 15, 'milk': 15, 'egg': 20, 'bread': 25}
        3. After restocking {'apple': 30, 'Banana': 30, 'carrot': 15, 'milk': 15, 'egg': 25, 'bread': 25}
        4. Updated Inventory after delete {'apple': 30, 'Banana': 30, 'milk': 15, 'egg': 25}
        5a. Is banana in inventory True
        5b. Is Orange in inventory False
                6. Product: apple count is: 30
                6. Product: Banana count is: 30
                6. Product: milk count is: 15
                6. Product: egg count is: 25
        7. Iterating inventory gives tuple: dict_items([('apple', 30), ('Banana', 30), ('milk', 15), ('egg', 25)])
        8. Product: egg  its count is: 25
        9. Count of apple 25
Copy after login

Set:
A set is an unordered collection of unique elements. Sets are mutable, but they do not allow duplicate elements.

Syntax:
botanical_garden = {'rose', 'lotus', 'Lily'}
botanical_garden.add('Jasmine')
botanical_garden.remove('Rose')
is_present_Jasmine = 'Jasmine' in botanical_garden

Above we can see to define a set, adding a values and removing it. If we add same elements in a set, it will through an error.

Also we can compare two sets similar to venn diagram. Like Union, difference, intersection of two data sets.

botanical_garden = {'Tuple', 'rose', 'Lily', 'Jasmine', 'lotus'}
rose_garden = {'rose', 'lotus', 'Hybiscus'}

common_flower= botanical_garden.intersection(rose_garden)
flowers_only_in_bg = botanical_garden.difference(rose_garden)
flowers_in_both_set = botanical_garden.union(rose_garden)

Output will be a set by default. 
If needed we can typecase into list using list(expression)
Copy after login

Tuple:
A tuple is an ordered collection of elements that is immutable, meaning it cannot be changed after it is created.

Syntax:

ooty_trip = ('Ooty', '2024-1-1', 'Botanical_Garden')
munnar_trip = ('Munar', '2024-06-06', 'Eravikulam National Park')
germany_trip = ('Germany', '2025-1-1', 'Lueneburg')
print('\t1. Trip details', ooty_trip, germany_trip)

#Accessing tuple using index
location = ooty_trip[0]
date = ooty_trip[1]
place = ooty_trip[2]

print(f'\t2a. Location: {location} Date: {date} Place: {place} ')

location, date, place =germany_trip # Assinging a tuple to 3 different variables
print(f'\t2b. Location: {location} Date: {date} Place: {place} ')

print('\t3. The count of ooty_trip is ',ooty_trip.count)

Output:
   1. Trip details ('Ooty', '2024-1-1', 'Botanical_Garden') ('Germany', '2025-1-1', 'Lueneburg')
   2a. Location: Ooty Date: 2024-1-1 Place: Botanical_Garden
   2b. Location: Germany Date: 2025-1-1 Place: Lueneburg
   3. The count of ooty_trip is  <built-in method count of tuple object at 0x0000011634B3DBC0>

Copy after login

Tuples can be accessed using index. The values of tuples can be assigned to multiple variables easily. We can combine two tuples which will create another tuple. But tuple cannot be modified.

The above is the detailed content of Python - Dictionary, Set, Tuple. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles