Dictionary in Python is a collection of keys values, used to store data values like a map, which, unlike other data types which hold only a single value as an element.

In some languages it is known as map or associative arrays.

dict = { ‘name’ : ‘udus’ , ‘age’ : 32 , ‘gender’ : ‘male’ }

Characterstics:

  • Mutable
  • Indexing has no meaning
  • keys can’t be duplicated
  • keys can’t be mutable items

Creating a Dictionary:

# Empty Dictionary
d = {}
print("Empty Dictionary:", d)

# 1D Dictionary
d1 = {'name': 'udus', 'gender': 'male'}
print("1D Dictionary:", d1)

# Dictionary with Mixed Keys
d2 = {(1, 2, 3): 1, 'hello': 'world'}
print("Dictionary with Mixed Keys:", d2)

# 2D Dictionary (JSON-like structure)
s = {
    'name': 'naksh',
    'college': 'bit',
    'sem': 4,
    'subjects': {
        'dsa': 50,
        'maths': 67,
        'english': 34
    }
}
print("2D Dictionary (JSON-like structure):", s)

# Using Sequence and dict Function
d4 = dict([('name', 'naksh'), ('age', 32), (3, 3)])
print("Using Sequence and dict Function:", d4)

# Duplicate Keys
d5 = {'name': 'naksh', 'name': 'nabin'}
print("Duplicate Keys:", d5)

# Mutable Items as Keys
d6 = {'name': 'naksh', (1, 2, 3): 2}
print("Mutable Items as Keys:", d6)

Explanation:

  • The code provides examples of creating dictionaries in Python using various methods.
  • Dictionaries can be created with different key-value pairs, including empty dictionaries, dictionaries with mixed keys, 2D dictionaries with nested structures, dictionaries created using sequences and the dict function, dictionaries with duplicate keys (with the latter value prevailing), and dictionaries with mutable items as keys.

Accessing Items in a Dictionary:

# Dictionary Definition
my_dict = {'name': 'Jack', 'age': 26}

# Using []
age_value = my_dict['age']
print("Accessing with []:", age_value)

# Using get
age_value_get = my_dict.get('age')
print("Accessing with get:", age_value_get)

# Nested Dictionary Access
maths_marks = s['subjects']['maths']
print("Nested Dictionary Access:", maths_marks)

Adding Key-Value Pairs to a Dictionary:

# Adding Key-Value Pair to d4
d4['gender'] = 'male'
print("Updated d4:", d4)

# Adding Another Key-Value Pair to d4
d4['weight'] = 72
print("Updated d4 with Weight:", d4)

# Adding Key-Value Pair to s
s['subjects']['ds'] = 75
print("Updated s:", s)

Explanation:

  • The first code block demonstrates how to access values in a dictionary using square brackets ([]) and the get method.
  • The second code block shows how to add key-value pairs to a dictionary using the assignment operator (=).
  • In the case of the nested dictionary s, a new key-value pair is added to the nested dictionary under the ‘subjects’ key.

Removing Key-Value Pairs from a Dictionary:

# Dictionary Definition
d = {'name': 'naksh', 'age': 32, 3: 3, 'gender': 'male', 'weight': 72}

# Using pop
d.pop(3)  # Removes the key-value pair with key 3
print("Dictionary after pop(3):", d)

# Using popitem
d.popitem()  # Removes and returns the last key-value pair
print("Dictionary after popitem():", d)

# Using del
del d['name']  # Removes the key-value pair with key 'name'
print("Dictionary after del['name']:", d)

# Using clear
d.clear()  # Removes all key-value pairs, resulting in an empty dictionary
print("Dictionary after clear():", d)

# Removing a Key-Value Pair from a Nested Dictionary
del s['subjects']['maths']
print("Updated s after deleting 'maths' from subjects:", s)

Explanation:

  • The code demonstrates various methods to remove key-value pairs from a dictionary.
  • The pop method removes the specified key and returns its value.
  • The popitem method removes and returns the last key-value pair in the dictionary.
  • The del statement can be used to remove a specific key-value pair.
  • The clear method removes all key-value pairs, leaving an empty dictionary.
  • In the case of the nested dictionary s, the del statement is used to remove the ‘maths’ key from the ‘subjects’ dictionary.

Editing a Key-Value Pair in a Dictionary:

# Editing a Key-Value Pair in the Nested Dictionary s
s['subjects']['dsa'] = 80
print("Updated s after editing 'dsa' to 80:", s)

Explanation:

  • The code modifies the value associated with the key ‘dsa’ in the nested dictionary ‘subjects’ of dictionary s.
  • The assignment s['subjects']['dsa'] = 80 sets the value for the key ‘dsa’ within the nested dictionary to 80.
  • The resulting dictionary s reflects the change in the ‘dsa’ value within the ‘subjects’ dictionary.

Dictionary Operations:

Membership Check:

# Membership Check
'name' in s

Iteration over Keys:

# Iterating over Keys
for key in s:
    print(key)

Explanation:

  • Membership Check ('name' in s): Checks whether the key ‘name’ is present in the dictionary s. The result is a Boolean value indicating the presence or absence of the key.
  • Iteration over Keys (for key in s): Iterates over the keys in the dictionary s. In this case, the keys are printed during the iteration.

Example:

# Dictionary Definition
d = {'name': 'shisir', 'gender': 'male', 'age': 33}

# Membership Check
is_name_present = 'name' in d
print("Is 'name' present in d:", is_name_present)

# Iterating over Keys
print("Keys in d:")
for key in d:
    print(key)

Explanation:

  • The membership check verifies whether the key ‘name’ is present in the dictionary d.
  • The iteration over keys prints each key in the dictionary d.

Dictionary Functions:

# Dictionary Definition
d = {'name': 'naksh', 'gender': 'male', 'age': 33}

# Length, Sorted, and Max
length_d = len(d)
print("Length of d:", length_d)
print("Original Dictionary:", d)
sorted_d_reverse = sorted(d, reverse=True)
print("Sorted Dictionary (Reverse):", sorted_d_reverse)
max_key = max(d)
print("Max Key in Dictionary:", max_key)

# Items, Keys, and Values
print("Original Dictionary:", d)
items_d = d.items()
print("Items in Dictionary:", items_d)
keys_d = d.keys()
print("Keys in Dictionary:", keys_d)
values_d = d.values()
print("Values in Dictionary:", values_d)

# Update
d1 = {1: 2, 3: 4, 4: 5}
d2 = {4: 7, 6: 8}
d1.update(d2)
print("Updated d1 after d1.update(d2):", d1)

Explanation:

  • Length (len(d)): Returns the number of key-value pairs in the dictionary d.
  • Sorted (sorted(d, reverse=True)): Returns a new list containing all keys from the dictionary d, sorted in reverse order.
  • Max (max(d)): Returns the maximum key in the dictionary d.
  • Items (d.items()): Returns a view of the dictionary’s key-value pairs as a list of tuples.
  • Keys (d.keys()): Returns a view of the dictionary’s keys as a list.
  • Values (d.values()): Returns a view of the dictionary’s values as a list.
  • Update (d1.update(d2)): Updates the dictionary d1 with the key-value pairs from dictionary d2. If keys in d2 already exist in d1, their values are updated. If not, they are added to d1.

Dictionary Comprehension

# Comprehension for First 10 Numbers and Their Squares
numbers_and_squares = {i: i**2 for i in range(1, 11)}
print("Numbers and Their Squares:", numbers_and_squares)

# Items in distances Dictionary
distances = {'delhi': 1000, 'mumbai': 2000, 'bangalore': 3000}
print("Items in distances Dictionary:", distances.items())

# Comprehension using Existing Dictionary (Converting distances from km to miles)
distances_miles = {key: value * 0.62 for (key, value) in distances.items()}
print("Distances in Miles:", distances_miles)

Explanation:

  • The first comprehension creates a dictionary (numbers_and_squares) with keys as the first 10 numbers and values as their squares using the expression i: i**2 in the comprehension.
  • The second print statement shows the items in the distances dictionary.
  • The third comprehension (distances_miles) uses the existing distances dictionary to create a new dictionary with the same keys but values converted from kilometers to miles using the expression value * 0.62.

Using zip for Dictionary Comprehension:

# Using zip to create a dictionary of days and temperatures in Celsius
days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
temp_C = [30.5, 32.6, 31.8, 33.4, 29.8, 30.2, 29.9]
days_and_temps = {day: temp for (day, temp) in zip(days, temp_C)}
print("Days and Temperatures (Celsius):", days_and_temps)

Using if Condition in Dictionary Comprehension:

# Using if condition to filter products with non-zero quantities
products = {'phone': 10, 'laptop': 0, 'charger': 32, 'tablet': 0}
non_zero_products = {key: value for (key, value) in products.items() if value > 0}
print("Non-Zero Quantity Products:", non_zero_products)

Explanation:

  • The first example uses zip to create a dictionary (days_and_temps) where keys are days and values are temperatures in Celsius.
  • The second example utilizes an if condition to filter out products with zero quantities, resulting in a dictionary (non_zero_products) containing only products with a quantity greater than 0.

Nested Comprehension to Print Tables:

# Nested Comprehension to print tables of numbers from 2 to 4
tables = {i: {j: i * j for j in range(1, 5)} for i in range(2, 5)}
print("Tables of Numbers from 2 to 4:")
print(tables)

Output:

Tables of Numbers from 2 to 4:
{
  2: {1: 2, 2: 4, 3: 6, 4: 8},
  3: {1: 3, 2: 6, 3: 9, 4: 12},
  4: {1: 4, 2: 8, 3: 12, 4: 16}
}

Explanation:

  • The nested comprehension {i: {j: i * j for j in range(1, 5)} for i in range(2, 5)} generates a dictionary where the outer keys are numbers from 2 to 4, and the inner dictionaries represent the tables for each number from 1 to 10.
  • The resulting tables dictionary contains the tables of numbers 2, 3, and 4 up to the multiplier 4.

2 Replies to “Dictionary in Python”

Leave a Reply

Your email address will not be published. Required fields are marked *