0% found this document useful (0 votes)
5 views2 pages

Python Sets Dictionaries Notes

This document provides an overview of sets and dictionaries in Python. It explains the characteristics and common methods of sets, such as adding and removing elements, as well as the structure and methods of dictionaries, including accessing key-value pairs. Example code snippets illustrate the usage of both data structures.

Uploaded by

shobithap088
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Python Sets Dictionaries Notes

This document provides an overview of sets and dictionaries in Python. It explains the characteristics and common methods of sets, such as adding and removing elements, as well as the structure and methods of dictionaries, including accessing key-value pairs. Example code snippets illustrate the usage of both data structures.

Uploaded by

shobithap088
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Python Notes - Sets and Dictionaries

Sets in Python
- A set is an unordered collection of unique items.
- Sets are defined using curly braces {} or using set().
- Example: my_set = {1, 2, 3}
- Duplicate elements are not allowed.
- No indexing in sets, use loops to access elements.

Common Set Methods:


- add(item): Adds a single element.
- update(iterable): Adds multiple elements.
- remove(item): Removes a specified element (error if not found).
- discard(item): Removes specified element (no error if not found).
- pop(): Removes a random element.
- clear(): Empties the entire set.

Example Code:
fruits = {'apple', 'banana', 'cherry'}
fruits.add('orange')
fruits.remove('banana')
for fruit in fruits:
print(fruit)

Dictionaries in Python
- A dictionary is a collection of key-value pairs.
- Defined using curly braces {} with key: value.
- Example: student = {'name': 'John', 'age': 18}
- Keys must be unique; values can be duplicated.

Common Dictionary Methods:


- keys(): Returns all keys.
- values(): Returns all values.
- items(): Returns key-value pairs.
- get(key): Returns value for a key.
- update(): Updates dictionary with another dictionary.

Example Code:
student = {'name': 'John', 'age': 18, 'grade': 'A'}
print(student['name'])
student['gender'] = 'Male'
student['grade'] = 'A+'
for key, value in student.items():
print(key, ':', value)

You might also like