Python Coding Practice - 4 (46 - 60 Questions)

Q45. Access nested dictionary value: users = {"u1": {"name":"A","city":"X"}} — get city of u1.
users = {"u1": {"name":"A","city":"X"}}
city = users[]['city']
Outer key is a string; use quotes inside brackets.
Answer: "u1"
Explanation: users["u1"] returns the inner dict; ['city'] accesses the city value.
Q46. Remove and return value for key 'age' from d = {'name':'A','age':20}.
d = {'name':'A','age':20}
val = d.( 'age' )
Method removes key and returns its value.
Answer: pop
Explanation: d.pop('age') removes the key and returns 20; KeyError if missing unless default provided.
Q47. Check if key 'k' exists in dictionary d efficiently.
d = {'a':1, 'b':2}
if in d:
  print("Found")
Membership test on dict checks keys by default.
Answer: k
Explanation: Use `if key in dict:` to test membership; it checks keys, which is O(1) average-time.
Q48. Create a list of even numbers from 1..10 using list comprehension.
evens = [ for i in range(1,11) if i % 2 == 0]
Expression should use the loop variable i.
Answer: i
Explanation: The comprehension `[i for i in range(1,11) if i%2==0]` yields even numbers 2,4,6,8,10.
Q49. Which list method inserts an element at a given index?
One method takes index and value.
Answer: insert()
Explanation: list.insert(index, value) inserts value at the specified index shifting later elements right.
Q50. Remove duplicates from list lst while preserving order (fill the expression).
lst = [1,2,2,3,1]
seen = set()
res = [x for x in lst if (x not in seen and (seen.add(x) or True))]
# The expression uses seen.add(x) to track seen items
Use a set to track seen items inside comprehension.
Answer: Use comprehension with seen.add(x) trick
Explanation: The comprehension keeps first occurrences and preserves order by checking membership and adding when first seen.
Q51. Tuple unpacking: assign x,y,z from t = (1,2,3).
t = (1,2,3)
= t
Comma-separated variable names on left.
Answer: x, y, z
Explanation: x, y, z = t assigns 1→x, 2→y, 3→z via unpacking.
Q52. Which set method removes an element without raising an error if missing?
One raises KeyError if element absent; the other does not.
Answer: discard()
Explanation: set.discard(x) removes x if present and does nothing if absent; remove(x) raises KeyError when missing.
Q53. Sort list nums = [3,1,2] in-place.
nums = [3,1,2]
nums.()
Method sorts list in place.
Answer: sort
Explanation: nums.sort() sorts the list in-place to [1,2,3]; sorted(nums) returns a new list.
Q54. Which string method returns a lowercase version?
Opposite of upper().
Answer: lower()
Explanation: s.lower() returns a new string with all characters converted to lowercase.
Q55. Reverse string s using slicing.
s = "abc"
rev = s[]
Use full slice with negative step.
Answer: ::-1
Explanation: s[::-1] returns the reversed string 'cba'.
Q56. Try/except: catch any exception and print 'Error'.
try:
  1/0
except :
  print("Error")
Base class for most built-in exceptions.
Answer: Exception
Explanation: `except Exception:` catches most runtime exceptions; catching specific exceptions is preferred.
Q57. File handling: open file 'data.txt' for writing.
f = open("data.txt", )
Mode for writing is "w".
Answer: "w"
Explanation: open(filename, "w") opens file for writing (creates/truncates file).
Q58. Lambda: create a function that returns x+1.
inc = (x): x + 1
Anonymous function keyword.
Answer: lambda
Explanation: `inc = lambda x: x+1` defines a small anonymous function that increments its argument.
Q59. Dictionary items(): returns what?
Method name suggests pairs.
Answer: A view of (key, value) pairs
Explanation: dict.items() returns a view object of (key, value) tuples suitable for iteration.
Q60. Frequency counting: increment count for ch using dict.get.
freq = {}
ch = 'a'
freq[ch] = freq.(ch, 0) + 1
Use safe dict access with default value.
Answer: get
Explanation: freq.get(ch, 0) returns current count or 0 if missing; adding 1 updates the frequency safely.

Post a Comment

0 Comments