Showing posts with label Python Data Structures. Show all posts
Showing posts with label Python Data Structures. Show all posts

Dictionaries in Python

← Back to Home

Python Dictionaries:



Dictionaries are python data structures which store the data in key-value pairs. These are like Maps in other similar programming languages.

Dictionaries are not ordered unlike strings, Lists and Tuples.

Keys uniquely define the items in a python dictionary. So duplicate keys are not allowed.

Keys are unique but values are not.

Keys must be of immutable types like strings, numbers and tuples.

Dictionary can contain any type of values.



Creating a Dictionary :

Each key is separated from its value by a colon(:)

The items are separated by commas

All the above paired items are enclosed in curly braces.


watch video below to demonstrate python dictionaries: 





Empty Dictionary:
       An empty dictionary without any item is created with just two curly braces.{}

Example:

              

Dictionary containing items: (create and display)




Accessing values from Dictionary:

Values can be accessed  using square brackets along with the key to obtain its value.

Example:



Both the print commands produces the corresponding values with keys "Name" and "Age".

If we attempt to access the data item which is not present in dictionary, we'll get error as





Updating Dictionary :

Dictionary can be updated by adding a new entry or a Key-Value pair, modifying an existing entry or deleting an existing entry :
Example:

In the above code the key 'Age' has the updated value from 25 to 16.
Also, there is a new entry where key is 'Department' with the value 'Finance'.(see Highlighted)


Deleting Dictionary Element

You can delete either an individual item or entire content of a dictionary.

Entire dictionary can also be deleted in a single operation.

Example 1:


If we now want to print the items, An exception is raised because after the command del dict, dictionary does not  exist.

Example 2:




 Properties of Dictionary Keys:

1. More than one entry per key is not allowed i.e duplicate keys are not allowed. When duplicate keys are assigned, only the last assigned (latest) key exists.

2. Keys must be immutable. i.e you can use strings, numbers and Tuples as dictionary keys . others are not allowed.



Built-in Dictionary functions:

1.  cmp : compares elements of both dict.

             cmp ( dict1 , dict2)

2.   len: Gives total length or the total number of elements in the dictionary.

             len(dict)

3.   str: produces a printable string representation of a dictionary.

            str(dict)

4.  type (variable) - returns the type of passed variable . If passed variable is dictionary, then it returns dictionary type.



Dictionary Methods:

Python uses following dictionary methods:

1.    dict.clear( )

2.    dict.copy( )

3.    dict.fromkeys( )

4.    dict.get(key, default = None)

5.    dict.has_key(key)

6.    dict.items( )

7.    dict.keys()

8.    dict.setdefault(key, default=None)

9.    dict.update(dict2)

10.  dict.values()


Python Tuples || Tuples in python

← Back to Home

🧾 Tuples in Python –  Beginner-Friendly 

One of the important data structures in Python is the tuple. In this article, we’ll explore what tuples are, how to use them, and why they’re useful.


✅ What is a Tuple?

A tuple is a collection of items that is:

  • Ordered: Items have a fixed position.

  • Immutable: You cannot change the items after the tuple is created.

  • Allows duplicates: You can have the same value more than once.

Think of a tuple like a list, you can’t modify it after creation.


📌 How to Create a Tuple

Creating a tuple is easy! Just use parentheses () and separate the items with commas.

# A tuple with numbers
numbers = (1, 2, 3, 4)

# A tuple with mixed data types
person = ("Alice", 25, "Engineer")

# A tuple with one item (note the comma!)
single_item = (5,)

🔍 Accessing Tuple Items

You can access tuple items by using their index, starting from 0.

person = ("Alice", 25, "Engineer")

print(person[0])  # Output: Alice
print(person[2])  # Output: Engineer

🚫 Tuples are Immutable

Once a tuple is created, you cannot change it:

person = ("Alice", 25, "Engineer")

# This will give an error
# person[1] = 30

If you need a changeable version, consider using a list instead.


🔁 Looping Through a Tuple

You can loop through a tuple using a for loop:

colors = ("red", "green", "blue")

for color in colors:
    print(color)

🔧 Tuple Methods

Even though tuples are immutable, they have a few useful methods:

  • .count(value) – Returns the number of times a value appears.

  • .index(value) – Returns the index of the first occurrence of the value.

data = (1, 2, 3, 2, 4)

print(data.count(2))  # Output: 2
print(data.index(3))  # Output: 2

📦 Tuple Packing and Unpacking

Packing means putting values into a tuple. Unpacking means assigning values from a tuple to variables.

# Packing
person = ("Bob", 30, "Doctor")

# Unpacking
name, age, job = person

print(name)  # Bob
print(age)   # 30

📊 When to Use a Tuple?

Use a tuple when:

  • You want to store a fixed collection of items.

  • You want to make sure the data cannot be changed.

  • You need to use the data as a key in a dictionary (tuples can be used as keys, but lists cannot).


✅ Quick Summary

Feature Tuple List
Mutable ❌ No ✅ Yes
Ordered ✅ Yes ✅ Yes
Allows Duplicates ✅ Yes ✅ Yes
Syntax (1, 2, 3) [1, 2, 3]

📚 Example: Tuple in a Real Program

# List of students with their scores (name, score)
students = [
    ("Alice", 85),
    ("Bob", 78),
    ("Charlie", 92)
]

for name, score in students:
    print(f"{name} scored {score} points.")

Watch video to understand tuple in python: 




💬 Final Thoughts

Tuples are a simple yet powerful feature in Python. Once you understand when and why to use them, they can help make your code cleaner, safer, and more efficient.

If you're new to Python, start by practicing with lists and tuples to get a good grip on how Python handles collections of data.

Tuples in Python

← Back to Home

Tuples :


Tuples are immutable list data structures in python. They are like lists but the only difference is, you can not change the content of the tuple unlike lists. Tuples are built-in data structures like lists.
These are useful at the times when you need to use the data structures which could not be modified at some situations..

Tuple is a immutable sequence of python objects.

Creating tuple:
                        Tuple can be created by putting comma-separated values. you can also put comma separated values between parenthesis.

Examples:
            tuple1 = ("India", "America", "France", "Russia", 2020, 1947);
            tuple2 = ( 2, 3, 5, 7, 11, 13);
            tuple3 = "a","b","c","d","e";

Empty tuple:
                      tuple = ( );


Like strings and lists tuple indices start from 0



The tuple indices can be Sliced, concatenate, and so on.


Accessing Tuple:

To access values in tuple, use square brackets for slicing along with index or indices for the values of particular index.

Example: There are two tuples  tuple1 and tuple2
                tuple1 = ("India", "America","Japan", "Germany",2020);
                tuple2 = (2,3,5,7,11,13,17);

           compute: tuple1[0] and tuple2[1:5]

Output:



Updating tuple : Tuples are immutable lists, you can not change the contents/items of any tuples.

portions of the tuple can be taken to create new tuple.

Example :  take two tuples tup1 and tup2 populated with following items
                   tup1 = (12, 24, 36, 48);
                   tup2 = ('Pre' , 'post');
now, perform
                   tup12 =  tup1  +  tup2

Output :



Deleting tuple: 

  •  Individual tuple element can not be deleted. 
  •  You can do it by creating new tuple, dropping the individual element.
  • use del keyword to delete the tuple.

Example :  take tuple1

               tuple1 = ("India", "America","Japan", "Germany",2020);
               
delete this by using
                      del  tuple1;

Output:



Tuple Operations: 


  • Length :   Length of the tuple 
                                e.g.      len (1,2,3)    will return 3
  • Concatenation:  concatenates two or more tuples
                               e.g      (1,2,4,5) + ( 6,7,8)  will result
                                            (1,2,4,5,6,7,8)
  • Repetition: Use astrisk (*) followed with number to repeat
                             e.g.      ('Hello',) * 3   will return
                                                  ('Hello','Hello','Hello')
  • Membership:    gives  TRUE if the element is a member or FALSE  if it is not the member.
                            e.g.    4 in (1,2,3,4,5)  will result TRUE 
                        while     6  in (1,2,3,4,5)  will result FALSE
  • Iteration:


Indexing and slicing 
                           Indexing and slicing works the same way as it does in strings.

                                                         you can refer to the post Lists in Python



Buil-in Tuple Functions:

  • cmp
                 compares two strings . it returns boolean value
                                 cmp (tuple1 , tuple2)
  • len
                returns the length of  tuple or items/elements in the tuple
                                 len (tuple1)
  • max
                 returns item from the tuple with maximum value. 
                                 max(tup1)
  • min

                   returns item from the tuple with minimum value. 
                                 min(tup1)
  • tuple(seq)
                      converts a list into tuple




Featured Post

Extra Challenge: Using References Between Documents

  🎯 💡 Extra Challenge: Using References Between Documents Here's an  Extra Challenge  designed to build on the original MongoDB mode...

Popular Posts