Append Dictionary Keys and Values (In order ) in dictionary using Python

AmitDiwan
Updated on 25-Mar-2026 18:35:02

877 Views

When you need to append dictionary keys and values in order, Python provides several approaches. The most straightforward method uses the list() function with .keys() and .values() methods to extract and concatenate them. Basic Approach Using list() and Concatenation This method converts dictionary keys and values to lists, then concatenates them ? my_dict = {"January": 1, "Feb": 2, "March": 3, "April": 4, "May": 5, "June": 6} print("The dictionary is:") print(my_dict) my_result = list(my_dict.keys()) + list(my_dict.values()) print("The ordered key and value are:") print(my_result) The dictionary is: {'January': 1, 'Feb': 2, 'March': ... Read More

Convert key-values list to flat dictionary in Python

AmitDiwan
Updated on 25-Mar-2026 18:34:43

685 Views

When working with dictionaries that contain lists as values, you may need to convert them into a flat dictionary where elements from the lists become key-value pairs. Python provides several approaches to achieve this transformation. Understanding the Problem A key-values list dictionary has keys mapped to lists of values. Converting to a flat dictionary means pairing corresponding elements from these lists into key-value pairs. Using zip() Method The most common approach uses zip() to pair corresponding elements from two lists ? my_dict = {'month_num': [1, 2, 3, 4, 5, 6], 'name_of_month': ['Jan', 'Feb', 'March', ... Read More

Extract tuples having K digit elements in Python

AmitDiwan
Updated on 25-Mar-2026 18:34:26

539 Views

When working with lists of tuples, you may need to extract tuples containing elements with a specific number of digits. This can be accomplished using list comprehension with the all() function and len() to check digit counts. Example Here's how to extract tuples where all elements have exactly K digits ? my_list = [(34, 56), (45, 6), (111, 90), (11, 35), (78, )] print("The list is :") print(my_list) K = 2 print("The value of K has been initialized to", str(K)) my_result = [sub for sub in my_list if all(len(str(elem)) == K for elem ... Read More

Python Program to Take in a String and Replace Every Blank Space with Hyphen

AmitDiwan
Updated on 25-Mar-2026 18:34:08

1K+ Views

When it is required to take a string and replace every blank space with a hyphen, the replace() method can be used. It takes two parameters: the blank space, and the value with which it needs to be replaced (hyphen in this case). Below is a demonstration of the same − Using replace() Method text = "Hello world Python programming" print("Original string:") print(text) modified_text = text.replace(' ', '-') print("Modified string:") print(modified_text) Original string: Hello world Python programming Modified string: Hello-world-Python-programming Interactive Example Here's an example that takes user input ... Read More

Python Program to Replace all Occurrences of 'a' with $ in a String

AmitDiwan
Updated on 25-Mar-2026 18:33:53

850 Views

When it is required to replace all the occurrences of 'a' with a character such as '$' in a string, Python provides multiple approaches. You can iterate through the string manually, use the built-in replace() method, or use string translation methods. Method 1: Using Manual Iteration This approach iterates through each character and builds a new string ? my_str = "Jane Will Rob Harry Fanch Dave Nancy" changed_str = '' for char in range(0, len(my_str)): if(my_str[char] == 'a'): changed_str += '$' ... Read More

Python Program to Find Element Occurring Odd Number of Times in a List

AmitDiwan
Updated on 25-Mar-2026 18:33:38

1K+ Views

When it is required to find an element that occurs odd number of times in a list, several approaches can be used. The most common methods include nested loops to count occurrences, using Python's Counter from collections module, or using XOR operations for optimization. Method 1: Using Nested Loops This method iterates through the list and counts occurrences of each element using nested loops ? def odd_occurrence(my_list, list_size): for i in range(0, list_size): count = 0 ... Read More

Python Program to Remove the nth Occurrence of the Given Word in a List where Words can Repeat

AmitDiwan
Updated on 25-Mar-2026 18:33:20

2K+ Views

When it is required to remove a specific occurrence of a given word in a list of words, given that the words can be repeated, a method can be defined that iterates through the list and increments a counter. If the count matches the specific occurrence, then that element can be deleted from the list. Example Below is a demonstration of removing the nth occurrence of a word from a list − def remove_word(my_list, my_word, N): count = 0 for i in range(0, len(my_list)): ... Read More

Superscript in Python plots

Rishikesh Kumar Rishi
Updated on 25-Mar-2026 18:33:05

12K+ Views

Superscript notation is essential for displaying scientific formulas and units in Python plots. Matplotlib supports LaTeX-style mathematical notation using the $\mathregular{}$ syntax to create superscripts and subscripts in titles, axis labels, and legends. Basic Superscript Syntax Use $\mathregular{text^{superscript}}$ format where the caret ^ indicates superscript and curly braces {} contain the superscript text ? import matplotlib.pyplot as plt # Simple superscript example plt.figure(figsize=(6, 4)) plt.text(0.5, 0.5, r'$\mathregular{x^2}$', fontsize=20, ha='center') plt.text(0.5, 0.3, r'$\mathregular{E=mc^2}$', fontsize=16, ha='center') plt.xlim(0, 1) plt.ylim(0, 1) plt.title('Basic Superscript Examples') plt.show() Physics Formula Plot with Superscripts Let's create a force vs ... Read More

Logarithmic Y-axis bins in Python

Rishikesh Kumar Rishi
Updated on 25-Mar-2026 18:32:40

4K+ Views

To plot logarithmic Y-axis bins in Python, we can use matplotlib's yscale() method to set a logarithmic scale. This is particularly useful when your data spans several orders of magnitude, making it easier to visualize trends that would be compressed on a linear scale. Steps to Create Logarithmic Y-axis Plot Create x and y data points using NumPy Set the Y-axis scale using the yscale() method Plot the x and y points using the plot() method Add labels and legend for better visualization Display the figure using the show() method Example Here's how to ... Read More

How to plot a time series in Python?

Rishikesh Kumar Rishi
Updated on 25-Mar-2026 18:32:18

4K+ Views

To plot a time series in Python using matplotlib, we can take the following steps − Create x and y points, using numpy. Plot the created x and y points using the plot() method. To display the figure, use the show() method. Basic Time Series Plot Here's a simple example that creates hourly data points for a full day ? import matplotlib.pyplot as plt import datetime import numpy as np plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True # Create datetime points for 24 hours x = np.array([datetime.datetime(2021, 1, 1, i, 0) ... Read More

Advertisements