PYTHON
LETS LEARN SOMETHING NEW
LECTURE 4
Dictionary and SET
DICTIONARY IN PYTHON
Dictionaries are used to store data values in key:value pairs
They are unordered, mutable(changeable) & don’t allow duplicate keys.
Dict[“Key”]=“Value”
NESTED DICTIONARIES
DICTIONARY METHODS
myDict.keys( ) #returns all keys
myDict.values( ) #returns all values
myDict.items( ) #returns all (key, val) pairs as tuples
myDict.get( “key““ ) #returns the key according to value
myDict.update( newDict ) #inserts the specified items to the dictionary
SET IN PYTHON
Set is the collection of the unordered items.
Each element in the set must be unique & mutable.
• nums = { 1, 2, 3, 4 }
• set2 = { 1, 2, 2, 2 } # it will store just set2={1,2}
• null_set = set( )
SET METHOD
• set.add( el ) #adds an element
• set.remove( el ) #removes the element
• set.clear( ) #empties the set
• set.pop( ) #removes a random value
• set.union( set2 ) #combines both set values & returns new
• set.intersection( set2 ) #combines common values & returns new
LETS PRACTICE
1. Store following word meanings in a python dictionary
table : “a piece of furniture”, “list of facts & figures”
cat : “a small animal”
LETS PRACTICE
2. You are given a list of subjects for students. Assume one classroom is required for 1
subject. How many classrooms are needed by all students.
”python”, “java”, “C++”, “python”, “javascript”,
“java”, “python”, “java”, “C++”, “C”
Ans: Take all the elements on a set. And count the len(set)…
LETS PRACTICE
3. enter marks of 3 subjects from the user and store them in a dictionary. Start with
an empty dictionary & add one by one. Use subject name as key & marks as value.
LETS PRACTICE
4. Figure out a way to store 9 & 9.0 as separate values in the set.
(You can take help of built-in data types)