Programming Essentials Python - Overview of Collections - Common Operations - dict and tuple

In this article, we will explore common operations that can be applied to collections like tuples and dictionaries in Python. The video tutorial linked below demonstrates these operations in action.

Click here to watch the video tutorial

Key Concepts Explanation

Tuple Operations

Tuples are immutable sequences in Python. Here are some key operations that can be performed on tuples:

  1. Check if an element exists in the tuple using the in keyword:
t = (1, 2, 3, 4)
1 in t
5 in t
  1. Get the number of elements in the tuple using the len function:
len(t)
  1. Sort the elements in the tuple (original tuple remains untouched) using the sorted function:
sorted(t, reverse=True)
  1. Perform arithmetic operations like sum, min, max, etc:
sum(t)

Dictionary Operations

Dictionaries are unordered collections of key-value pairs in Python. Here are some common operations on dictionaries:

  1. Check if a key exists in the dictionary using the in keyword:
d = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
1 in d
5 in d
'a' in d
  1. Get the number of key-value pairs in the dictionary using the len function:
len(d)
  1. Sort the keys in the dictionary (original dictionary remains untouched) using the sorted function:
sorted(d)
  1. Perform arithmetic operations like sum, min, max, etc (these operations are performed on keys):
sum(d)

Hands-On Tasks

Here are some hands-on tasks for you to try out:

  1. Create a tuple with your favorite numbers and check if a specific number is present in the tuple.
  2. Create a dictionary with some key-value pairs and find the sum of keys in the dictionary.

Conclusion

In this article, we covered common operations that can be applied to tuples and dictionaries in Python. Practice these operations to strengthen your understanding. Join the community to engage with fellow learners and expand your Python knowledge further!

Common Operations

There are some functions which can be applied on all collections. Here we will see details related to tuple and dict using Python as programming language.

  • in - check if element exists in the tuple

  • in can also be used on dict. It checks if the key exists in the dict.

  • len - to get the number of elements.

  • sorted - to sort the data (original collection will be untouched). Typically, we assign the result of sorting to a new collection.

  • sum, min, max, etc - arithmetic operations. In case of dict, the operations will be performed on key.

  • There can be more such functions.
    t = (1, 2, 3, 4) # tuple
    1 in t
    5 in t
    len(t)
    sorted(t, reverse=True)
    sum(t)
    d = {1: ‘a’, 2: ‘b’, 3: ‘c’, 4: ‘d’} # dict
    1 in d
    5 in d
    ‘a’ in d
    len(d)
    sorted(d) # only sorts the keys
    sum(d) # applies only on keys

Watch the video tutorial here