0% found this document useful (0 votes)
0 views

Dictionaries in Python (1)

The document provides various Python code snippets demonstrating how to manipulate dictionaries, including sorting by value, adding keys, concatenating dictionaries, checking for key existence, iterating over items, generating squares, summing values, merging dictionaries, and removing duplicates. Each section includes sample code and expected output. The examples cover a wide range of dictionary operations, making it a comprehensive guide for working with dictionaries in Python.

Uploaded by

harsha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Dictionaries in Python (1)

The document provides various Python code snippets demonstrating how to manipulate dictionaries, including sorting by value, adding keys, concatenating dictionaries, checking for key existence, iterating over items, generating squares, summing values, merging dictionaries, and removing duplicates. Each section includes sample code and expected output. The examples cover a wide range of dictionary operations, making it a comprehensive guide for working with dictionaries in Python.

Uploaded by

harsha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Sort (ascending and descending) a dictionary by

value

# Import the 'operator' module, which provides functions for common


operations like sorting.
import operator

# Create a dictionary 'd' with key-value pairs.


d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}

# Print the original dictionary 'd'.
print('Original dictionary : ',d)

# Sort the items (key-value pairs) in the dictionary 'd' based on the
values (1st element of each pair).
# The result is a list of sorted key-value pairs.
sorted_d = sorted(d.items(), key=operator.itemgetter(1))

# Print the dictionary 'sorted_d' in ascending order by value.


print('Dictionary in ascending order by value : ',sorted_d)

# Convert the sorted list of key-value pairs back into a dictionary.


# The 'reverse=True' argument sorts the list in descending order by
value.
sorted_d = dict( sorted(d.items(), key=operator.itemgetter(1),
reverse=True))

# Print the dictionary 'sorted_d' in descending order by value.


print('Dictionary in descending order by value : ',sorted_d)

Sample Output:

Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}


Dictionary in ascending order by value : [(0, 0), (2, 1), (1, 2), (4,
3), (3, 4)]
Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}
Python: Add a key to a dictionary
# Create a dictionary 'd' with two key-value pairs. d = {0: 10, 1: 20} #
Print the original dictionary 'd'. print(d) # Update the dictionary 'd'
by adding a new key-value pair {2: 30}. d.update({2: 30}) # Print the
dictionary 'd' after the update, which now includes the new key-value
pair. print(d)

Copy
Sample Output:

{0: 10, 1: 20}


{0: 10, 1: 20, 2: 30}

Concatenate following dictionaries to create a new


one
3. Concatenate Dictionaries

Write a Python script to concatenate the following dictionaries to create a new one.

Visual Presentation:
Sample Solution:

Python Code:

# Create three dictionaries 'dic1', 'dic2', and 'dic3' with key-value


pairs.

dic1 = {1: 10, 2: 20}

dic2 = {3: 30, 4: 40}

dic3 = {5: 50, 6: 60}

# Create an empty dictionary 'dic4' that will store the combined


key-value pairs from 'dic1', 'dic2', and 'dic3'. dic4 = {}

# Iterate through each dictionary ('dic1', 'dic2', and 'dic3') using a


loop. for d in (dic1, dic2, dic3):

# Update 'dic4' by adding the key-value pairs from the current dictionary
'd'. dic4.update(d)

# Print the combined dictionary 'dic4' containing all the key-value pairs
from 'dic1', 'dic2', and 'dic3'. print(dic4)

Copy
Sample Output:

{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

Check whether a given key already exists in a


dictionary
Python Code:
# Create a dictionary 'd' with key-value pairs.

d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

# Define a function 'is_key_present' that takes an argument 'x'.

def is_key_present(x):

# Check if 'x' is a key in the dictionary 'd'. if x in d:

# If 'x' is present in 'd', print a message indicating that the key is


present.

print('Key is present in the dictionary')

else:

# If 'x' is not present in 'd', print a message indicating that the key
is not present.

print('Key is not present in the dictionary')

# Call the 'is_key_present' function with the argument 5 to check if 5 is


a key in the dictionary.

is_key_present(5)

# Call the 'is_key_present' function with the argument 9 to check if 9 is


a key in the dictionary.

is_key_present(9)

Copy
Sample Output:

Key is present in the dictionary


Key is not present in the dictionary
Python: Iterate over dictionaries using for loops

5. Iterate Over Dictionary Using For Loops

Write a Python program to iterate over dictionaries using for loops.

Sample Solution:

Python Code:

# Create a dictionary 'd' with key-value pairs.

d = {'x': 10, 'y': 20, 'z': 30}

# Iterate through the key-value pairs in the dictionary using a for loop.
# 'dict_key' represents the key, and 'dict_value' represents the value
for each pair.

for dict_key, dict_value in d.items():

# Print the key followed by '->' and the corresponding value.


print(dict_key, '->', dict_value)​

Copy
Sample Output:

x -> 10
y -> 20
z -> 30
Python: Generate and print a dictionary that
contains a number in the form (x, x*x)

6. Generate Dictionary of Numbers and Their Squares

Write a Python script to generate and print a dictionary that contains a number (between 1
and n) in the form (x, x*x).

# Prompt the user to input a number and store it in the variable 'n'.

n = int(input("Input a number "))

# Create an empty dictionary 'd' to store the square of numbers.

d = dict()

# Iterate through numbers from 1 to 'n' (inclusive).

for x in range(1, n + 1):

# Calculate the square of each number and store it in the dictionary 'd'
with the number as the key.

d[x] = x * x

# Print the dictionary 'd' containing the squares of numbers from 1 to


'n'. print(d)

Sample Output:

10
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
Python: Sum all the items in a dictionary
Write a Python program to sum all the items in a dictionary.

Sample Solution:

Python Code:

# Create a dictionary 'my_dict' with key-value pairs.

my_dict = {'data1': 100, 'data2': -54, 'data3': 247}

# Use the 'sum' function to calculate the sum of all values in the
'my_dict' dictionary.

# 'my_dict.values()' extracts the values from the dictionary, and 'sum'


calculates their sum.

result = sum(my_dict.values())

# Print the result, which is the sum of the values. print(result)

Sample Output:

293

Python: Iterate over dictionaries using for loops


Write a Python program to iterate over dictionaries using for loops.

Python Code:

# Create a dictionary 'd' with color names as keys and corresponding


numerical values as values.
d = {'Red': 1, 'Green': 2, 'Blue': 3}

# Iterate through the key-value pairs in the dictionary 'd' using a for
loop.

for color_key, value in d.items():

# Print the color name, 'corresponds to', and its corresponding numerical
value.

print(color_key, 'corresponds to ', d[color_key])

Sample Output:

Red corresponds to 1
Green corresponds to 2
Blue corresponds to 3

Python: Print a dictionary where the keys are


numbers between 1 and 15 and the values are
square of keys
Write a Python script to print a dictionary where the keys are numbers between 1 and 15
(both included) and the values are the square of the keys.

Python Code:

# Create an empty dictionary 'd' to store the squares of numbers.

d = dict()

# Iterate through numbers from 1 to 15 (inclusive).


for x in range(1, 16):

# Calculate the square of each number and store it in the dictionary 'd'
with the number as the key.

d[x] = x ** 2

# Print the dictionary 'd' containing the squares of numbers from 1 to


15.

print(d)

Sample Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11:
121, 12: 144, 13: 169, 14: 196, 15:
225}

Python: Merge two Python dictionaries


Python Code:

# Create the first dictionary 'd1' with key-value pairs.

d1 = {'a': 100, 'b': 200}

# Create the second dictionary 'd2' with key-value pairs.

d2 = {'x': 300, 'y': 200}

# Create a new dictionary 'd' and initialize it as a copy of 'd1'.

d = d1.copy()

# Update the dictionary 'd' by adding key-value pairs from 'd2'.


d.update(d2)
# Print the dictionary 'd' after combining the key-value pairs from 'd1'
and 'd2.

print(d)

Sample Output:

{'x': 300, 'y': 200, 'a': 100, 'b': 200}

Python: Multiply all the items in a dictionary


Python Code:

# Create a dictionary 'my_dict' with keys 'data1', 'data2', and 'data3',


along with their respective values.

my_dict = {'data1': 100, 'data2': -54, 'data3': 247}

# Initialize a variable 'result' to 1. This variable will store the


product of all values in the dictionary.

result = 1 # Iterate through the keys in the 'my_dict' using a for loop.
for key in my_dict:

# Multiply the current 'result' by the value associated with the current
key in 'my_dict'.

result = result * my_dict[key]

# Print the final 'result,' which is the product of all values in the
dictionary.

print(result)

Sample Output:

-1333800
Python: Remove a key from a dictionary
Write a Python program to remove a key from a dictionary.

Visual Presentation:

Sample Solution:
Python Code:

# Create a dictionary 'myDict' with key-value pairs.

myDict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Print the original dictionary 'myDict'. print(myDict)

# Check if the key 'a' exists in the 'myDict' dictionary.

if 'a' in myDict:

# If 'a' is in the dictionary, delete the key-value pair with the key
'a'.

del myDict['a']

# Print the updated dictionary 'myDict' after deleting the key 'a' (if it
existed).

print(myDict)

Sample Output:

{'a': 1, 'b': 2, 'c': 3, 'd': 4}


{'b': 2, 'c': 3, 'd': 4}

Python: Map two lists into a dictionary


Python Code:

# Create a list 'keys' containing color names.

keys = ['red', 'green', 'blue']

# Create another list 'values' containing corresponding color codes in


hexadecimal format.
values = ['#FF0000', '#008000', '#0000FF']

# Use the 'zip' function to pair each color name with its corresponding
color code and create a list of tuples.

# Then, use the 'dict' constructor to convert this list of tuples into a
dictionary 'color_dictionary'.

color_dictionary = dict(zip(keys, values))

# Print the resulting 'color_dictionary' containing color names as keys


and their associated color codes as values.

print(color_dictionary)

Sample Output:

{'red': '#FF0000', 'green': '#008000', 'blue': '#0000FF'}

Python: Sort a dictionary by key


Write a Python program to sort a given dictionary by key

Python Code:

# Create a dictionary 'color_dict' with color names as keys and their


corresponding color codes in hexadecimal format as values.

color_dict = { 'red': '#FF0000', 'green': '#008000', 'black': '#000000',


'white': '#FFFFFF' }

# Iterate through the keys of the 'color_dict' dictionary after sorting


them in lexicographical order.

for key in sorted(color_dict):


# Print each key-value pair where '%s' is a placeholder for the key and
its associated color code.

print("%s: %s" % (key, color_dict[key])) ​

Sample Output:

black: #000000
green: #008000
red: #FF0000
white: #FFFFFF

Python: Get the maximum and minimum value in a


dictionary

Python Code:

# Create a dictionary 'my_dict' with key-value pairs.

my_dict = {'x': 500, 'y': 5874, 'z': 560}

# Find the key with the maximum value in 'my_dict' using the 'max'
function and a lambda function.

# The 'key' argument specifies how the maximum value is determined.


key_max = max(my_dict.keys(),

key=(lambda k: my_dict[k]))

# Find the key with the minimum value in 'my_dict' using the 'min'
function and a lambda function.

# The 'key' argument specifies how the minimum value is determined.


key_min = min(my_dict.keys(),
key=(lambda k: my_dict[k]))

# Print the maximum value by using the 'key_max' to access the


corresponding value in 'my_dict'.

print('Maximum Value: ', my_dict[key_max])

# Print the minimum value by using the 'key_min' to access the


corresponding value in 'my_dict'.

print('Minimum Value: ', my_dict[key_min])

Sample Output:

Maximum Value: 5874


Minimum Value: 500

Python: Get a dictionary from an object's fields


Python Code:

# Define a class 'dictObj' that inherits from the 'object' class.

class dictObj(object):

# Define the constructor method '__init__' for initializing object


attributes.

def __init__(self):

# Initialize attributes 'x', 'y', and 'z' with string values.

self.x = 'red' self.y = 'Yellow' self.z = 'Green'

# Define a method 'do_nothing' that doesn't perform any actions


(placeholder).
def do_nothing(self): pass

# Create an instance 'test' of the 'dictObj' class.

test = dictObj()

# Print the '__dict__' attribute of the 'test' object, which contains its
attribute-value pairs.

print(test.__dict__)

Sample Output:

{'x': 'red', 'y': 'Yellow', 'z': 'Green'}

Python: Remove duplicates from Dictionary


Last update on April 21 2025 13:01:04 (UTC/GMT +8 hours)

17. Remove Duplicates from the Dictionary

Write a Python program to remove duplicates from the dictionary.

Visual Presentation:
Sample Solution:

Python Code:

# Create a nested dictionary 'student_data' containing information about


students with unique IDs.

student_data = { 'id1': { 'name': ['Sara'], 'class': ['V'],


'subject_integration': ['english, math, science'] }, 'id2': { 'name':
['David'], 'class': ['V'], 'subject_integration': ['english, math,
science'] }, 'id3': { 'name': ['Sara'], 'class': ['V'],
'subject_integration': ['english, math, science'] }, 'id4': { 'name':
['Surya'], 'class': ['V'], 'subject_integration': ['english, math,
science'] } }

# Create an empty dictionary 'result' to store unique student records.


result = {}

# Iterate through the key-value pairs in the 'student_data' dictionary


using a for loop.

for key, value in student_data.items():

# Check if the current 'value' (student record) is not already in the


'result' dictionary.

if value not in result.values():

# If the 'value' is not already in 'result', add it to 'result' with its


corresponding 'key'.

result[key] = value

# Print the 'result' dictionary containing unique student records.


print(result)
Sample Output:

{'id2': {'subject_integration': ['english, math, science'],


'class': ['V'], 'name': ['David']},
'id4': {'subje
ct_integration': ['english, math, science'],
'class': ['V'], 'name': ['Surya']},
'id1': {'subject_integration'
: ['english, math, science'],
'class': ['V'], 'name': ['Sara']}}

Python: Combine two dictionary adding values for


common keys

Python Code:

# Import the 'Counter' class from the 'collections' module. from


collections

import Counter

# Create two dictionaries 'd1' and 'd2' with key-value pairs.

d1 = {'a': 100, 'b': 200, 'c': 300}

d2 = {'a': 300, 'b': 200, 'd': 400}

# Use the 'Counter' class to create counter objects for 'd1' and 'd2',
which count the occurrences of each key.

# Then, add the counters together to merge the key-value pairs and their
counts.

d = Counter(d1) + Counter(d2)
# Print the resulting merged dictionary 'd'. print(d)

Sample Output:

Counter({'b': 400, 'd': 400, 'a': 400, 'c': 300})

Python: Print all unique values in a dictionary


Python Code:

# Create a list 'L' containing dictionaries with key-value pairs.

L = [{"V": "S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"},


{"VII": "S005"}, {"V": "S009"}, {"VIII": "S007"}]

# Print a message indicating the start of the code section.


print("Original List: ", L)

# Create a set 'u_value' to store unique values found in the dictionaries


within the list 'L'.

# Use a set comprehension to iterate through the dictionaries and values


and extract unique values.

u_value = set(val for dic in L for val in dic.values())

# Print the unique values stored in the 'u_value' set.

print("Unique Values: ", u_value)

Sample Output:

Original List: [{'V': 'S001'}, {'V': 'S002'}, {'VI': 'S001'}, {'VI':


'S005'}, {'VII': 'S005'}, {'V': 'S009'},
{'VIII': 'S007'}]
Unique Values: {'S009', 'S002', 'S007', 'S005', 'S001'}

You might also like