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.
Dictionary (dict):
- Dictionary is collection of key value pair, where each key is associated with a value
- Data can be retrieved based on key value(Key based search) as the keys are required to be unique.
- 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'])
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
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)
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> </built-in>
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!

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

Python provides a variety of ways to download files from the Internet, which can be downloaded over HTTP using the urllib package or the requests library. This tutorial will explain how to use these libraries to download files from URLs from Python. requests library requests is one of the most popular libraries in Python. It allows sending HTTP/1.1 requests without manually adding query strings to URLs or form encoding of POST data. The requests library can perform many functions, including: Add form data Add multi-part file Access Python response data Make a request head

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

PDF files are popular for their cross-platform compatibility, with content and layout consistent across operating systems, reading devices and software. However, unlike Python processing plain text files, PDF files are binary files with more complex structures and contain elements such as fonts, colors, and images. Fortunately, it is not difficult to process PDF files with Python's external modules. This article will use the PyPDF2 module to demonstrate how to open a PDF file, print a page, and extract text. For the creation and editing of PDF files, please refer to another tutorial from me. Preparation The core lies in using external module PyPDF2. First, install it using pip: pip is P

This tutorial demonstrates how to leverage Redis caching to boost the performance of Python applications, specifically within a Django framework. We'll cover Redis installation, Django configuration, and performance comparisons to highlight the bene

Natural language processing (NLP) is the automatic or semi-automatic processing of human language. NLP is closely related to linguistics and has links to research in cognitive science, psychology, physiology, and mathematics. In the computer science

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Linux new version
SublimeText3 Linux latest version

Notepad++7.3.1
Easy-to-use and free code editor

Dreamweaver CS6
Visual web development tools
