Python - Dictionary, Set, Tuple

WBOY
Release: 2024-08-12 22:35:37
Original
460 people have browsed it

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 
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!

source:dev.to
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!