0% found this document useful (0 votes)
34 views3 pages

Python Dictionary Operations Guide

The document contains multiple Python code snippets that demonstrate various dictionary operations, including creating dictionaries for products and employees, searching for states and their capitals, counting character frequencies in a string, identifying words that start and end with the same letter, and counting vowels and consonants in the English alphabet. Each snippet includes user input and displays relevant information based on the operations performed. Overall, the document serves as a practical guide for manipulating dictionaries in Python.

Uploaded by

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

Python Dictionary Operations Guide

The document contains multiple Python code snippets that demonstrate various dictionary operations, including creating dictionaries for products and employees, searching for states and their capitals, counting character frequencies in a string, identifying words that start and end with the same letter, and counting vowels and consonants in the English alphabet. Each snippet includes user input and displays relevant information based on the operations performed. Overall, the document serves as a practical guide for manipulating dictionaries in Python.

Uploaded by

Mimk Legend
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Write a Python code to create a dictionary containing four products with their names as keys and

their sales as values, respectively. Display the dictionary with the names of the products and also the
product having the highest sale.

name=input("Enter your name :")


dict={'Apple':65,'Brinjal':82,'Banana':75}
for x in dict:
print(x,':',dict[x])

high_item= max(dict)
print("Highest product is",high_item)

Write a Python code to assign three dictionaries, each containing the name, age, and salary of an
employee. The company has decided to increase the salary by 20% for the employees whose age is 55
years and above. Display the original and updated dictionaries.

empl3 = {'name': 'Alice', 'age': 56, 'salary': 50000}


empl2 = {'name': 'Bob', 'age': 45, 'salary': 60000}
empl1 = {'name': 'Charlie', 'age': 55, 'salary': 70000}

empl=[empl1,empl2,empl3]
print(empl)

for emp in empl:


if emp['age']>=55:
emp['salary']*=1.2

for emp in empl:


print(emp)

Write a Python code to assign two dictionaries, one containing states' names as values and the other
containing the corresponding capitals' names. Now, enter a state name and search for it in the
dictionary of states' names. If found, then display the state name along with its capital name,
otherwise, display "State name not found."

states = {'Gujarat': 'Gandhinagar','Maharashtra': 'Mumbai','Rajasthan': 'Jaipur','Karnataka':


'Bengaluru','Tamil Nadu': 'Chennai'}

sn=input("Enter the state name:")

if sn in states:
print("The state is",sn,"it's capital is",states[sn])

else:
print("State not found")
Write a Python code to input a string and find the frequencies of each character of the string. Finally,
it returns as a dictionary with the key as the character and its value as its frequency in the given
string.

str=input("Enter the stringL:")


l=list(str)
freq=[[Link](ele) for ele in l]
d=dict(zip(l,freq))
print(d)

Write a Python code to create a dictionary containing English words corresponding to their suitable
keys. Display such words which start and end with the same letter. Also, display the frequency of all
such words.

words_dict = {'apple': 1,'banana': 2,'level': 3,'madam': 4,'racecar': 5,'civic': 6,'hello': 7,'radar': 8}


same_letterwords={}
for word,freq in words_dict.items():
if word[0] == word[-1]:
same_letterwords[word] = freq

print(same_letterwords)

for x in same_letterwords:
print(x,':',same_letterwords[x])

Write a Python code to assign a dictionary containing letters of the English alphabet as values along
with suitable keys. Find and display the number of vowels and consonants.

# Create a dictionary with letters of the English alphabet


alphabet_dict = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h',
9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o',
16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v',
23: 'w', 24: 'x', 25: 'y', 26: 'z'}

# Vowel list
vowels = ['a', 'e', 'i', 'o', 'u']

# Counters
vowel_count = 0
consonant_count = 0

# Loop to count vowels and consonants


for letter in alphabet_dict.values():
if letter in vowels:
vowel_count += 1
else:
consonant_count += 1

# Display the counts


print("Number of vowels:", vowel_count)
print("Number of consonants:", consonant_count)

Common questions

Powered by AI

The code handles strings containing repeated characters by creating a list comprehension [l.count(ele) for ele in l] that calculates the frequency of each character (including repeats). It then constructs a dictionary using these frequencies where each character is paired with its count. This process ensures that repeating characters are accurately reflected in their respective frequency values within the dictionary .

The Python code attempts to find the product with the highest sale by using the max function on the dictionary 'dict'. However, this usage is flawed because the max function, as applied, operates on keys rather than values. To correctly identify the highest sale, the code should iterate over dictionary items and compare the sales (values) instead of keys .

The code defines a dictionary 'alphabet_dict' with letters as values and uses a predefined 'vowels' list to count the vowels. It iterates over the values of 'alphabet_dict' and checks if each letter is a vowel using an 'if' condition. A counter 'vowel_count' is incremented for vowels, otherwise 'consonant_count' is incremented for consonants. The final output displays the number of vowels and consonants as 'Number of vowels: 5' and 'Number of consonants: 21' respectively .

The code could be optimized by using a dictionary comprehension directly instead of looping and conditionally adding entries to 'same_letterwords'. A more concise approach: same_letterwords = {word: freq for word, freq in words_dict.items() if word[0] == word[-1]}. This one-liner produces the same result but with less code and potential variables, enhancing readability and maintaining functionality .

In the code, list comprehension [l.count(ele) for ele in l] is used to create a list of counts for each character in the input string. It calls l.count(ele) for each character 'ele' to determine how many times it appears in the list 'l', which represents the input string. This efficient method facilitates the subsequent creation of a dictionary mapping each character to its frequency .

The logical flaw lies in using max(dict) which evaluates the maximum key by lexicographical order instead of determining the product with the highest sale. To correct this, the max function should be applied on the dictionary values with key-value pairs using a lambda function, like: max(dict.items(), key=lambda item: item[1]), which would correctly return the key of the item with the highest value .

The code iterates over the dictionary 'words_dict' and checks the condition if word[0] == word[-1] for each word, which identifies words starting and ending with the same letter. It adds these words and their frequencies to a new dictionary 'same_letterwords'. Finally, it displays these words and their corresponding frequencies by iterating over 'same_letterwords' and printing each entry .

The code defines a list 'empl' containing dictionaries for each employee with their name, age, and salary. It iterates through this list and checks if an employee's age is 55 or above. If true, their salary is increased by 20% using the operation emp['salary'] *= 1.2. The original dictionaries are first printed to show the initial state of each employee's details, followed by the updated dictionaries after applying the salary adjustments .

The code converts the input string into a list of characters and calculates the frequency of each character using a list comprehension: [l.count(ele) for ele in l]. It then creates a dictionary 'd' pairing each character with its frequency via the zip function. This resultant dictionary is printed, showing character frequencies .

The code prompts the user to input a state name and checks if this name is present in the 'states' dictionary using an 'if' condition (sn in states). If the state is found, it retrieves and prints both the state and its capital using states[sn]. If the state name is not found, it outputs 'State not found'. This structure efficiently handles data retrieval from the dictionary and provides feedback for absent entries .

You might also like