[Go to site: main page, start]

0% found this document useful (0 votes)
7 views21 pages

Dictionary Python Notes

The document provides a comprehensive overview of dictionaries in Python, detailing their structure, key characteristics, and various functions for accessing and manipulating data. It covers topics such as nested dictionaries, iteration, and common operations like adding, updating, and removing key-value pairs. Additionally, it includes practical examples and coding questions to reinforce understanding of dictionary usage.

Uploaded by

sheksuboor
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)
7 views21 pages

Dictionary Python Notes

The document provides a comprehensive overview of dictionaries in Python, detailing their structure, key characteristics, and various functions for accessing and manipulating data. It covers topics such as nested dictionaries, iteration, and common operations like adding, updating, and removing key-value pairs. Additionally, it includes practical examples and coding questions to reinforce understanding of dictionary usage.

Uploaded by

sheksuboor
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

Introduction to Dictionary (Python)

️ What is a Dictionary?
A dictionary is a data type that stores data in the form of key-value pairs.

️ Syntax / Structure:
d = {key1: value1, key2: value2}
️ Important Points:
• Dictionary is written inside curly brackets {}
• Key and value are separated by a colon :
• Each key-value pair is separated by a comma ,
Example:
student = {"name": "Amit", "age": 14}
️ In this example:
• "name" is a key: "Amit" is its value
• "age" is a key:14 is its value
️ Keys must be unique (no duplicates allowed)
️ Values can be duplicated
️ Dictionary is mutable (can be changed or updated after creation)

📘 Iteration in Dictionaries (Python)


️ Dictionary Example:
️ Student = {"name": "John", "class": "6th","roll_no": 23}

Accessing a Value:
️ print(Student[/"roll_no"])
️ Output:️ 23

Iterating Through Keys:


️ for x in Student:
️ print(x)
️ Output:️ name️ class️ roll_no(\”n”)
Iterating Through Values (Using Keys):
️ for x in Student:
️ print(Student[x])
️ Output:️ John 6th️ 23(\”n”)
️ Using values() Function:
for x in [Link]():
print(x)
️ Output:️ John 6th️ 23
️ Using items() Function:
for x, y in [Link]():
️ print(x, ":", y)
️ Output:️ name : John class : 6th️ roll_no : 23
Summary: 😂
• ️ for x in dict → keys
• ️ [Link]() → values
• ️ [Link]() → key + value

📘 Dictionary Functions (Part 1)


️ Dictionary Example:
Student = {"name": "John", "class": "6th", "roll_no": 23}

1️⃣ get() Function #️ Returns value of a given key


️ x = [Link]("name")
️ print(x)
️ Output:️ John
If key not found:
️ x = [Link]("age")
️ print(x)
️ Output:️ None

️⃣ keys() Function # Returns all keys of the dictionary

x = [Link]()
️print(x)
️ Output:️ dict_keys(['name', 'class', 'roll_no'])
x = [Link]()
print(x)
️ Output:️ dict_values(['John', '6th', 23])

4️⃣ items() Function # Returns key-value pairs as tuples


️ x = [Link]()
️ print(x)
️ Output:️ dict_items([('name', 'John'), ('class', '6th'), ('roll_no', 23)])

5️⃣ copy() Function Creates a copy of the dictionary


x = [Link]()
print(x)
️ Output:️ {'name': 'John', 'class': '6th', 'roll_no': 23}
➢ Summary:
️ ge️t() → ge️t value️ s️afe️ly
️ ke️ys️() → all ke️ys️
️ value️s️() → all value️s️
️ ite️ms️() → ke️y-value pairs
️ copy() → duplicate️ dictionary
📘 Dictionary Functions (Part 2)
️ Dictionary Example:
Student = {"name": "John", "class": "6th", "roll_no":23}
1️⃣ setdefault() Function Returns the value of a key
️ If key does NOT exist, it inserts the key with a default value
️ Case 1: Key already exists
x = [Link]("roll_no", 24)
print(x)
️ Output:️ 23
️ Explanation:️ "roll_no" already exists, so its value (23) is returned
️ No change in dictionary
️ Case 2: Key does NOT exist
x = [Link]("age", 15)
print(x)
️ Output:️ 15
️ Dictionary becomes:{"name": "John", "class": "6th", "roll_no": 23,"age": 15}

2️⃣ update() Function # Updates existing key OR adds new


key-value pair
[Link]({"class": "7th"})
[Link]({"age": 15})
print(Student)
️ Output:️ {'name': 'John', 'class': '7th', 'roll_no': 23, 'age': 15}

3️⃣ pop() Function # Removes a specific key and returns its value

x = [Link]("class")
print(x)
️ Output:️ 7th
️ Dictionary after removal:
️ {'name': 'John', 'roll_no': 23, 'age': 15}

4️⃣ popitem() Function #️ Removes the last inserted key-value pair

x = [Link]()
print(x)
️ Output:️ ('age', 15)

5️⃣ clear() Function:️ # Removes all elements from dictionary


[Link]()
print(Student)
️ Output:️ {}
️ Summary:
️ s️e️tde️fault() → ge️t or ins️e️rt de️fault value️
️ update️() → modify/add data
️ pop() → re️move️ s️pe️cific ke️y
️ popite️m() → re️move️ las️t pair
️ cle️ar() → e️mpty dictionary
📘 Nested Dictionaries (Python)
️ What is a Nested Dictionary?
️ A nested dictionary is a dictionary inside another dictionary
️ It is used to store multiple records in a structured way
️ Example:
️ Employees = {
️ 1: {"Name": "John", "Age": 23, "Gender": "male"},
️ 2: {"Name": "Lisa", "Age": 24, "Gender": "female"},
️ 3: {"Name": "Peter", "Age": 22, "Gender": "male"}
️ }
🔑 Important Concept (Very Important)
• ️ Keys cannot be dictionaries
️ Dictionary keys must be immutable (like int, string, tuple) ✅ and
sets,dict,list ❌
️ ❌ Invalid:
️ { {"a":1} : "value" } → Error
• ️ Values CAN be dictionaries ✅
️ That is why nested dictionaries are possible
️ ✔️ Valid:
️ { 1: {"Name": "John"} } ✅
️ How many dictionaries can be used?
️ There is no fixed limit You can store multiple dictionaries as values
️ Even deeper nesting is possible (dictionary inside dictionary)

Accessing Data

️ Full inner dictionary:

️ print(Employees[1]) Output: {'Name': 'John', 'Age': 23, 'Gender': 'male'}


️ Specific value (deep access):
️ print(Employees[1]["Name"]) Output:️ John

Key Points
• ️ Keys → must be unique and immutable
• ️ Values → can be anything (list, tuple, dictionary, etc.)

📘 Q1: Sort a Dictionary by Value


️d = {"A": 12, "B": 23, "C": 16, "D": 45}
sorted_d = dict( sorted([Link](), key=lambda x: x[1]) )
print(sorted_d)
️ Output:{'A': 12, 'C': 16, 'B': 23, 'D': 45}
Explanation:
• ️ [Link]() → dictionary ko (key, value) pairs me convert karta hai
• ️ sorted(...) → in pairs ko sort karta hai
• ️ key=lambda x: x[1] → sorting value ke basis par ho rahi hai (x[1] = value)
• ️ dict(...) → wapas dictionary bana deta hai

📘 Q2: Keys (1 to 15) and Values = Square

d = {}
for i in range(1, 16):
d[i] = i * i
print(d)
️ Output:️ {1: 1, 2: 4, 3: 9, ..., 15: 225}
Explanation:
• ️ range(1, 16) → 1 se 15 tak numbers deta hai
• ️ d[i] = i * i → har number ka square store ho raha hai
• ️ dictionary me key = number, value = uska square

📘 Q3: Multiply All Items in Dictionary
️d = {"A": 12, "B": 23, "C": 16, "D": 45}
result = 1
for value in [Link](): result = result * value
print(result)
️ Output:198720
Explanation:
• ️ [Link]() → sirf values deta hai (12, 23, 16, 45)
• ️ result = 1 → starting value (multiplication ke liye)
• ️ loop me har value se multiply ho raha hai
• ️ final result = sab values ka product

📘 Q4: Sort a Dictionary by Key
d = {"A": 12, "B": 23, "C": 16, "D": 45}
sorted_d = dict( sorted([Link]()) )
print(sorted_d)
️ Output:️ {'A': 12, 'B': 23, 'C': 16, 'D': 45}
Explanation:
• ️ [Link]() → (key, value) pairs banata hai
• ️ sorted(...) → default me key ke basis par sort karta hai
• ️ dict(...) → dobara dictionary me convert

📘 LECTURE 23 – Dictionary Basics
️ What is a Dictionary?
• ️ A dictionary stores data in key–value [Link] key is unique
and maps to a value
➢ ️ Why Important (Data Science)
• ️ Used for JSON / API data
• ️ Fast lookup (O(1))
• ️ Used in ML mappings (labels, features)
️ Creating Dictionary
1. Simple Dictionary
d = {"name": "John", "age": 20} Output:️ {'name': 'John', 'age': 20}

2. Different Data Types


d = {"name": "John", "age": 20,"marks":[80,90],"status":True}
️ Output:️ {'name': 'John', 'age': 20, 'marks': [80, 90], 'status': True}

3. Empty Dictionary
d = {} Output:️ {}

4. dict() Constructor
d = dict(name="John", age=20) Output:️ {'name': 'John',
'age':20}
️ Dictionary Comprehension
d = {x: x*x for x in range(1, 6)} Output:️ {1: 1, 2: 4, 3: 9, 4:16,5:25}
Explanation:Loop runs from 1 to 5;️ Key = number, Value = square

📘 LECTURE 24 – Characteristics & Access


• ️ Before Python 3.7 → Unordered
• ️ Python 3.7+ → Ordered ✅
• ️ Not index-based
• ️ Access using keys
• ️ No duplicate keys
d = {"a": 10, "a": 20} Output:️ {'a': 20}
• ️ Keys must be immutable
• ️ Allowed: int, string, tuple
• ️ Not allowed: list
️ Access Values

d = {"name": "John", "age": 20}


print(d["name"])
️ Output: John
️ Membership Test
print("name" in d)
️ Output: True
📘 LECTURE 25 – Nested Dictionary
employees = { 1: {"name": "John", "age": 23}, 2:
{"name": "Lisa", "age":24}}
print(employees)
️ Output:️ {1: {'name': 'John', 'age': 23}, 2: {'name': 'Lisa', 'age': 24}}

Access Nested Value
print(employees[1]["name"])
️ Output:️ John
️ Explanation: employees[1] → inner dictionary;️ ["name"] → value
📘 LECTURE 26 – Operations
️ Add / Update
d = {"A": 10}
d["B"] = 20 d["A"] = 50
print(d)
Output: {'A': 50, 'B': 20}
️ Update Method
d = {"A": 10}
[Link]({"A": 100, "B": 200})
print(d)
Output: {'A': 100, 'B': 200}
️ pop()
d = {"A": 10, "B": 20}
x = [Link]("A")
print(x)
print(d)
️ Output:️ 10
️ {'B': 20}
del
d = {"A": 10, "B": 20}
del d["A"]
print(d)
️ Output: {'B': 20}
️ clear()
d = {"A": 10, "B": 20}
[Link]()
print(d)
️ Output:️ { }
️ len()
d = {"A": 10, "B": 20}
print(len(d))
️ Output:2
📘 MCQs
️ Add key-value? → d[key] = value ✅
️ Get keys? → [Link]() ✅
📘 CODING QUESTIONS (PROPER)
✅ Q1: Book Dictionary
book_writing = { "Python Programming": 4.5,
"Data Science Handbook": 4.8,
"Machine Learning Basics": 4.2 }
if "Python Programming" in book_writing:
print("Found")
else:
print("Not Found")
titles = list(book_writing.keys())
print(titles)
️ Output:️ Found
️ ['Python Programming', 'Data Science Handbook', 'Machine Learning Basics']
✅ Q2: Fruit Stock
fruit_stock = { "Apple": 10, "Banana": 15, "Orange": 8,
"Grape": 20 }
for fruit, stock in fruit_stock.items():
print("Fruit:", fruit, "Stock:", stock)
️ Output:️ Fruit: Apple Stock: 10
️ Fruit: Banana Stock: 15
️ Fruit: Orange Stock: 8
️ Fruit: Grape Stock: 20
✅ Q3: Inventory Program (Perfect)
products = { }
for i in range(3):
pid = int(input("Enter Product ID: "))
name = input("Enter Product Name: ")
products[pid] = name
print(products)
️# Sample Input:
️#101, Laptop️ 102, Mouse 103, Keyboard
️ Output:
️ {101: 'Laptop', 102: 'Mouse', 103: 'Keyboard'}
• ️ Explanation:
• ️ Empty dictionary created
• ️ Loop runs 3 times
• ️ User input stored as key-value
• ️ Final dictionary printed
📘 FINAL PRACTICE
• ️ Create dictionary and print keys
• ️ Check key existence
• ️ Update value
• ️ Remove key
• ️ Count items

🟢 EASY LEVEL (1–10)


1. Create Dictionary
**Problem:** Create a dictionary with keys as names and values as
ages. Return the dictionary.
**Input:** names= ["Amit","Riya"],
ages= [25,30]
**Output:** {"Amit": 25, "Riya": 30}
**Solution:**
def create_dict(names, ages):
res = {}
for i in range(len(names)):
res[names[i]] = ages[i]
return res
• **Explanation:** We loop through the length of the names list. For every
index *i*, we create a new entry in our dictionary where the name is the
**Key** and the age is the **Value**.
2. Access Value
**Problem:** Return value of given key from dictionary.
**Input:**
d= {"a":10, "b":20},
key="b"
**Output:** 20
**Solution:**
def get_val(d, key):
return d[key]
• **Explanation:** In Python, you can look up a value by placing the key
ins️ide️ s️quare️ bracke️ts️ [ ]. It’s️ like️ looking up a word in a ph️ys️ical
dictionary.
3. Check Key Exists
**Problem:** Return true if key exists in dictionary.
**Input:** d= {"x":1, "y":2}, key="x"
**Output:** true
**Solution:**
def check_key(d, key):
return key in d
• **Explanation:** The in keyword is the most efficient way to check for a
key's presence. It returns a Boolean (True/False).
4. Count Keys
**Problem:** Return total number of keys in dictionary.
**Input:** d= {"a":1, "b":2, "c":3}
**Output:** 3
**Solution:**
def count_keys(d):
return len(d)
• **Explanation:** Just like with lists or strings, the len() function tells you
how many "key-value pairs" exist in the dictionary.
5. Sum of Values
**Problem:** Return sum of all dictionary values.
**Input:** d= {"a":10, "b":20, "c":30}
**Output:** 60
**Solution:**
def sum_values(d):
return sum([Link]())
• **Explanation:** [Link]() extracts all the numbers into a list-like format,
and sum() adds them all up.
6. Update Value
**Problem:** Update value of a given key.
**Input:** d= {"a":10}, key="a", new_value=50
**Output:** {"a":50}
**Solution:**
def update_val(d, key, new_value):
d[key] = new_value
return d
• **Explanation:** Dictionaries are **mutable**, meaning you can change
their contents. Re-assigning a value to an existing key simply overwrites
the old one.
7. Delete Key
**Problem:** Remove a key from dictionary.
**Input:** d= {"a":10, "b":20}, key="a"
**Output:** {"b":20}
**Solution:**
def delete_key(d, key):
if key in d:
del d[key]
return d
• **Explanation:** The del keyword removes the specific key and its
associated value from the memory of that dictionary.
8. Get All Keys
**Problem:** Return list of all keys.
**Input:** d= {"a":1, "b":2}
**Output:** ["a", "b"]
**Solution:**
def get_keys(d):
return list([Link]())
• **Explanation:** Using .keys() gives us a view of the keys, and wrapping
it in list() converts it into a standard list format.
➢ Same que repeated
🟢 1. Create Dictionary
Problem: Create a dictionary using names as keys and ages as values
def create_dict(names, ages):
result = {}
for i in range(len(names)):
result[names[i]] = ages[i]
return result
print(create_dict(["Amit","Riya"], [25,30]))
Output:
{'Amit': 25, 'Riya': 30}

• Explanation:Two lists are given. We match them using index. Each name
becomes key and age becomes value, so a dictionary is created step by
step.

🟢 2. Access Value
Problem: Return value of a given key
def get_val(d, key):
return d[key]
print(get_val({"a":10,"b":20}, "b"))
Output:20

• Explanation: We directly access the value using the key. Dictionary


lookup is very fast.

🟢 3. Check Key Exists


Problem: Check if a key exists
def check_key(d, key):
return key in d
print(check_key({"x":1,"y":2}, "x"))
Output:True

Explanation:"in" checks whether the key is present. It returns True or False.


🟢 4. Count Keys
Problem: Count total keys
def count_keys(d):
return len(d)
print(count_keys({"a":1,"b":2,"c":3}))
Output:3

• Explanation:len() returns number of key-value pairs in dictionary.

🟢 5. Sum of Values
Problem: Sum all values
def sum_values(d):
return sum([Link]())
print(sum_values({"a":10,"b":20,"c":30}))
Output:60

• Explanation:.values() gives all values and sum() adds them.

🟢 6. Update Value
Problem: Update value of a key
def update_val(d, key, new_value):
d[key] = new_value
return d
print(update_val({"a":10}, "a", 50))
Output:{'a': 50}

• Explanation:Assigning a new value replaces the old value because


dictionary is mutable.

🟢 7. Delete Key
Problem: Remove a key
def delete_key(d, key):
if key in d:
del d[key]
return d
print(delete_key({"a":10,"b":20}, "a"))
Output:{'b': 20}

• Explanation:We first check if key exists, then delete it using del.

🟢 8. Get All Keys


Problem: Return all keys
def get_keys(d):
return list([Link]())
print(get_keys({"a":1,"b":2}))
Output:['a', 'b']

• Explanation:.keys() gives keys, list() converts them to list.

🟢 9. Get All Values


Problem: Return all values
def get_vals(d):
return list([Link]())
print(get_vals({"a":1,"b":2}))
Output:[1, 2]
Explanation:.values() gives all values of dictionary.

🟢 10. Merge Dictionaries


Problem: Merge two dictionaries
def merge_dicts(d1, d2):
[Link](d2)
return d1
print(merge_dicts({"a":1}, {"b":2}))
Output:{'a': 1, 'b': 2}

Explanation:update() adds all items of second dictionary into first one.


🟡 11. Character Frequency
Problem: Count frequency of each character in a string
def char_freq(s):
freq = {}
for char in s:
freq[char] = [Link](char, 0) + 1
return freq
print(char_freq("banana"))
Output:{'b': 1, 'a': 3, 'n': 2}
Explanation (deep but simple):
So here input is "banana". We want to count how many times each character appears.
Step-by-step:
• Start with empty dictionary → freq = {}
• First character = 'b'
→ not present → [Link]('b',0) gives 0 → 0+1 = 1
→ freq = {'b':1}
• Next character = 'a'
→ not present → becomes 1
→ freq = {'b':1, 'a':1}
• Next = 'n'
→ freq = {'b':1, 'a':1, 'n':1}
• Next = 'a' again
→ already present → current value = 1 → now 1+1 = 2
→ freq = {'b':1, 'a':2, 'n':1}
• Next = 'n' again → becomes 2
• Next = 'a' again → becomes 3
Final dictionary shows count of each character.
👉 Important idea:
[Link](x,0) means
“agar pehli baar hai → 0 lo, warna purani value lo ”

🟡 12. Word Frequency


Problem: Count frequency of each word in a sentence
def word_freq(s):
words = [Link]()
freq = {}
for word in words:
freq[word] = [Link](word, 0) + 1
return freq
print(word_freq("I love Python I love coding"))
Output:{'I': 2, 'love': 2, 'Python': 1, 'coding': 1}

Explanation:Here input is a sentence, not characters. So first we convert it into a list of words:
"I love Python I love coding"
→ ["I","love","Python","I","love","coding"]
Now same logic as previous question:
• "I" → 1
• "love" → 1
• "Python" → 1
• "I" again → becomes 2
• "love" again → becomes 2
• "coding" → 1
👉 So difference from previous question:
• There we looped over characters
• Here we loop over words But logic SAME hai.

🟡 13. Invert Dictionary


Problem: Swap keys and values
def invert_dict(d):
result = {}
for key, value in [Link]():
result[value] = key
return result
print(invert_dict({"a":1,"b":2}))
Output:{1: 'a', 2: 'b'}
Explanation:Original dictionary:{'a':1, 'b':2}
We loop through pairs:
• key='a', value=1 → new pair → 1:'a'
• key='b', value=2 → new pair → 2:'b'
👉 So we reverse the mapping.
⚠ Important note:
Values must be unique, warna overwrite ho jayega.
🟡 14. Find Key with Maximum Value
Problem: Return key with highest value
def max_key(d):
return max(d, key=[Link])
print(max_key({"a":10,"b":25,"c":5}))
Output:'b'
Explanation:Dictionary is:{'a':10, 'b':25, 'c':5}
Normally max() checks keys alphabetically.
But we give extra instruction → key=[Link]
👉 Meaning: “compare using values”
So Python compares:
• a → 10
• b → 25
• c→5
Maximum value = 25 → belongs to 'b'
So output = 'b'
🟡 15. Sort Dictionary by Keys
Problem: Sort dictionary by keys
def sort_by_key(d):
items = sorted([Link]())
return dict(items)
print(sort_by_key({"b":2,"a":1,"c":3}))
Output:{'a': 1, 'b': 2, 'c': 3}
Explanation:Original order:{'b':2, 'a':1, 'c':3}
Step-by-step:
• [Link]() → [('b',2), ('a',1), ('c',3)]
• sorted() → [('a',1), ('b',2), ('c',3)]
• dict() → back to dictionary
👉 Sorting is done based on keys automatically.
🟡 16. Sort Dictionary by Values
Problem: Sort dictionary by values
def sort_by_val(d):
items = sorted([Link](), key=lambda x: x[1])
return dict(items)
print(sort_by_val({"a":3,"b":1,"c":2}))
Output:{'b': 1, 'c': 2, 'a': 3}
Explanation:Here we don't want to sort by keys, we want values.
Each item looks like: ('a',3)
👉 x[0] = key
👉 x[1] = value
So lambda x: x[1] means → sort based on value
Sorting becomes:
• ('b',1)
• ('c',2)
• ('a',3)
🟡 17. Group by First Letter
Problem: Group words by first letter
def group_by_first(words):
res = {}
for w in words:
first = w[0]
if first not in res:
res[first] = []
res[first].append(w)
return res
print(group_by_first(["apple","ant","bat","ball"]))
Output:{'a': ['apple', 'ant'], 'b': ['bat', 'ball']}
Explanation:We group words based on first letter:
• "apple" → first = 'a' → create list → ['apple']
• "ant" → same 'a' → add → ['apple','ant']
• "bat" → new key 'b' → ['bat']
• "ball" → same 'b' → ['bat','ball']
👉 So dictionary stores groups.
🟡 18. Count Occurrence in List
Problem: Count numbers
def count_nums(nums):
res = {}
for n in nums:
res[n] = [Link](n, 0) + 1
return res
print(count_nums([1,2,2,3,1]))
Output:{1: 2, 2: 2, 3: 1}
Explanation:Exactly same as character frequency.
👉 Only difference:
• earlier → characters
• now → numbers
Logic SAME hai.
🟡 19. Remove Keys with Specific Value
Problem: Remove keys having a given value
def remove_by_val(d, val):
res = {}
for k, v in [Link]():
if v != val:
res[k] = v
return res
print(remove_by_val({"a":10,"b":20,"c":10}, 10))
Output:{'b': 20}
Explanation:We create new dictionary.
Check each pair:
• 'a':10 → remove
• 'b':20 → keep
• 'c':10 → remove
👉 Only values not equal to 10 are kept.
🟡 20. Nested Dictionary Access
Problem: Access inner value
def get_nested(d):
return d["user"]["age"]
print(get_nested({"user":{"name":"Amit","age":25}}))
Output:25
Explanation:Structure is:"user" → gives inner dictionary
then "age" → gives value
👉 So:d["user"] → {"name":"Amit","age":25}
d["user"]["age"] → 25

🔥 FINAL REAL UNDERSTANDING


Ab honestly dekh:
👉 11,12,18 → SAME logic (counting)
👉 17 → grouping👉 19 → filtering👉 15,16 → sorting👉 20 → nested access
🔴 21. Two Sum
Problem: Find indices of two numbers whose sum = target
def two_sum(nums, target):
seen = {}
for i in range(len(nums)):
num = nums[i]
diff = target - num
if diff in seen:
return [seen[diff], i]
seen[num] = i
print(two_sum([2,7,11,15], 9))
Output: [0,1]
Explanation:nums=[2,7,11,15], target=9
i=0 → num=2 → diff=7 → store {2:0}
i=1 → num=7 → diff=2 → found → return [0,1]
👉 store + check pair

🔴 22. Group Anagrams


Problem: Group words having same letters
def group_anagrams(words):
res = {}
for w in words:
key = "".join(sorted(w))
if key not in res:
res[key] = []
res[key].append(w)
return list([Link]())
print(group_anagrams(["eat","tea","tan","ate","nat","bat"]))
Output: [['eat','tea','ate'],['tan','nat'],['bat']]
Explanation:sort word → same letters → same key
"eat","tea","ate" → "aet"
👉 group by sorted form

🔴 23. First Non-Repeating Character


Problem: Return index of first unique character
def first_unique(s):
freq = {}
for c in s:
freq[c] = [Link](c,0)+1
for i in range(len(s)):
if freq[s[i]]==1:
return i
return -1
print(first_unique("leetcode"))
Output: 0
Explanation:count → l:1,e:3,t:1,...
scan → first count=1 → 'l' → index 0
👉 frequency + check

🔴 24. Subarray Sum = K


Problem: Count subarrays whose sum = k
def subarray_sum(nums,k):
count=0
curr=0
prefix={0:1}
for n in nums:
curr+=n
if curr-k in prefix:
count+=prefix[curr-k]
prefix[curr]=[Link](curr,0)+1
return count
print(subarray_sum([1,1,1],2))
Output: 2
Explanation: running sum → 1,2,3
check curr-k → 2-2=0(found), 3-2=1(found)
👉 total subarrays = 2👉 prefix sum logic
🔴 25. Merge and Sum Keys
Problem: Merge dictionaries and add common keys
def merge_and_sum(d1,d2):
res=[Link]()
for k,v in [Link]():
res[k]=[Link](k,0)+v
return res
print(merge_and_sum({"a":1,"b":2},{"b":3,"c":4}))
Output: {'a':1,'b':5,'c':4}
Explanation:'b' → 2+3=5
'c' → new → add
👉 get() handles both

🔴 26. Check Dictionaries Equal


Problem: Check if two dictionaries are equal
def are_equal(d1,d2):
return d1==d2
print(are_equal({"a":1,"b":2},{"b":2,"a":1}))
Output: True
Explanation:Python compares keys + values, not order
{'a':1,'b':2} == {'b':2,'a':1} → True
👉 same data → equal

🔴 27. Find Duplicate Values


Problem: Find duplicate values in dictionary
def find_dupes(d):
seen=set()
dupes=set()
for v in [Link]():
if v in seen:
[Link](v)
else:
[Link](v)
return list(dupes)
print(find_dupes({"a":1,"b":2,"c":1}))
Output: [1]
Explanation:1 → seen
2 → seen
1 again → duplicate
👉 track seen values

🔴 28. Flatten Nested Dictionary


Problem: Convert nested dictionary into single level
def flatten(d,parent=''):
res={}
for k,v in [Link]():
new_key=parent+"."+k if parent else k
if isinstance(v,dict):
[Link](flatten(v,new_key))
else:
res[new_key]=v
return res
print(flatten({"a":{"b":1}}))
Output: {'a.b':1}
Explanation:"a" → inside dict
join keys → "a.b"
👉 recursion + key joining
🔴 29. Top K Frequent
Problem: Find k most frequent elements
def top_k(nums,k):
freq={}
for n in nums:
freq[n]=[Link](n,0)+1
items=sorted([Link](),key=lambda
x:x,reverse=True)
res=[]
for i in range(k):
[Link](items[i][0])
return res
print(top_k([1,1,1,2,2,3],2))
Output: [1,2]
Explanation:count → {1:3,2:2,3:1}
sort → highest first
take top k → [1,2]👉 frequency + sorting
🔴 30. LRU Cache
Problem: Simulate least recently used cache
def lru_cache(capacity,ops):
cache={}
order=[]
for op in ops:
p=[Link]()
if p[0]=="put":
k=int(p[1]);v=int(p[2])
if k in cache:
[Link](k)
elif len(cache)>=capacity:
old=[Link](0)
del cache[old]
cache[k]=v
[Link](k)
elif p[0]=="get":
k=int(p[1])
if k in cache:
[Link](k)
[Link](k)
return cache[k]
return None
print(lru_cache(2,["put 1 1","put 2 2","get 1"]))
Output: 1
Explanation:
store items + track order
least used → first element remove
used item → move to end
👉 LRU = Least Recently Used

🔥 FINAL REVISION (VERY IMPORTANT)


👉 90% questions = only these patterns:
• freq[x]=[Link](x,0)+1 → counting
• key in d → checking
• d[k]=v → storing
• sorted() → ordering
• get() → safe access
• recursion → nested

You might also like