Dictionary and Sets

Dictionary and Sets

Dictionary is a collection of key-value pairs.

Syntax:

''' a = {“key”: “value”,

“alok”: “code”,

“marks” : “100”,

“list”: [1,2,9]}

a[“key”]  # Prints value

a[“list”]           # Prints [1,2,9] '''

Copy

Properties of Python Dictionaries

1.     It is unordered

2.     It is mutable

3.     It is indexed

4.     It cannot contain duplicate keys

Dictionary Methods

Consider the following dictionary,

a = {“name”: “alok”,

          “from”: “India”,

          “marks”: [92,98,96]}

Copy

1.     items() : returns a list of (key,value) tuple.

2.     keys() : returns a list containing dictionary’s keys.

3.     update({“friend”: “Sam”}) : updates the dictionary with supplied key-value pairs.

4.     get(“name”) : returns the value of the specified keys (and value is returned e.g., “Alok” is returned here)

More methods are available on docs.python.org

Sets in Python

Set is a collection of non-repetitive elements.

S= Set()          # No repetition allowed!

 

S.add(1)

 

S.add(2)

 

# or Set = {1,2}

Copy

If you are a programming beginner without much knowledge of mathematical operations on sets, you can simply look at sets in python as data types containing unique values.

Properties of Sets

1.     Sets are unordered # Elements order doesn’t matter

2.     Sets are unindexed # Cannot access elements by index

3.     There is no way to change items in sets

4.     Sets cannot contain duplicate values

Operations on Sets

Consider the following set:

S = {1,8,2,3}

Copy

1.     Len(s) : Returns 4, the length of the set

2.     remove(8) : Updates the set S and removes 8 from S

3.     pop() : Removes an arbitrary element from the set and returns the element removed.

4.     clear() : Empties the set S

5.     union({8, 11}) : Returns a new set with all items from both sets. #{1,8,2,3,11}

6.     intersection({8, 11}) : Returns a set which contains only items in both sets. #{8}

 

Chapter 5 – Practice Set

1.     Write a program to create a dictionary of Hindi words with values as their English translation. Provide the user with an option to look it up!

2.     Write a program to input eight numbers from the user and display all the unique numbers (once).

3.     Can we have a set with 18(int) and “18”(str) as a value in it?

4.     What will be the length of the following set S:

S = Set()

 

S.add(20)

 

S.add(20.0)

 

S.add(“20”)

Copy

What will be the length of S after the above operations?

5.     S = {}, what is the type of S?

6.     Create an empty dictionary. Allow 4 friends to enter their favorite language as values and use keys as their names. Assume that the names are unique.

7.     If the names of 2 friends are the same; what will happen to the program in Program 6?

8.     If the languages of two friends are the same; what will happen to the program in Program 6?

9.     Can you change the values inside a list which is contained in set S

S = {8712, “alok”, [12]}