[go: up one dir, main page]

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

Python Dictionary

The document provides a comprehensive overview of Python dictionaries, including their structure as collections of key-value pairs and various methods for manipulation. It details methods like get(), keys(), values(), items(), update(), pop(), and more, along with examples and outputs for each method. Additionally, it includes multiple-choice questions and practical programs to illustrate dictionary usage and operations.
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)
3 views21 pages

Python Dictionary

The document provides a comprehensive overview of Python dictionaries, including their structure as collections of key-value pairs and various methods for manipulation. It details methods like get(), keys(), values(), items(), update(), pop(), and more, along with examples and outputs for each method. Additionally, it includes multiple-choice questions and practical programs to illustrate dictionary usage and operations.
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

Python Dictionary

 A dictionary is a collection of key-value pairs, where keys must be unique and immutable.

my_dict = {"name": "Alice", "age": 25}

All Dictionary Methods with Syntax, Explanation & Examples

1. dict.get(key, default)

 Gets the value for the given key. Returns default if key not found.

d = {"a": 1, "b": 2}
print(d.get("a")) # Output: 1
print(d.get("c", "NotFound")) # Output: NotFound

2. dict.keys()

 Returns all keys in the dictionary.

d = {"a": 1, "b": 2}
print(d.keys()) # Output: dict_keys(['a', 'b'])

3. dict.values()

 Returns all values in the dictionary.

print(d.values()) # Output: dict_values([1, 2])

4. dict.items()

 Returns a view of key-value pairs.

print(d.items()) # Output: dict_items([('a', 1), ('b', 2)])

5. dict.update(other_dict)

 Updates the dictionary with key-value pairs from another dictionary.

d = {"a": 1}
d.update({"b": 2, "a": 3})
print(d) # Output: {'a': 3, 'b': 2}

6. dict.pop(key, default)
 Removes the specified key and returns its value.
 If key not found, returns default or raises error.

d = {"a": 1, "b": 2}
print(d.pop("a")) # Output: 1
print(d.pop("x", "NA")) # Output: NA

7. dict.popitem()

 Removes and returns the last inserted (key, value) pair.

d = {"a": 1, "b": 2}
print(d.popitem()) # Output: ('b', 2)

8. dict.setdefault(key, default)

 Returns the value of key. If key is not found, inserts it with default value.

d = {"a": 1}
print(d.setdefault("a", 100)) # Output: 1
print(d.setdefault("b", 200)) # Output: 200
print(d) # Output: {'a': 1, 'b': 200}

9. dict.clear()

 Removes all items from the dictionary.

d = {"x": 10}
d.clear()
print(d) # Output: {}

10. dict.copy()

 Returns a shallow copy of the dictionary.

d1 = {"a": 1}
d2 = d1.copy()
d2["a"] = 5
print(d1) # Output: {'a': 1}

11. dict.fromkeys(iterable, value=None)

 Creates a new dictionary with keys from iterable and a common value.

keys = ["x", "y"]


d = dict.fromkeys(keys, 0)
print(d) # Output: {'x': 0, 'y': 0}
12. in operator (not a method)

 Checks if a key exists in dictionary.

d = {"a": 1}
print("a" in d) # Output: True
print("z" in d) # Output: False

Dictionary Iteration
for key, value in d.items():
print(key, value)

Summary Table of Methods


Method Description
get() Get value by key
keys() Returns all keys
values() Returns all values
items() Returns all key-value pairs
update() Merges two dictionaries
pop() Removes key and returns value
popitem() Removes last key-value pair
setdefault() Sets default if key is missing
clear() Empties the dictionary
copy() Returns shallow copy
fromkeys() Creates new dict from keys

Dictionary Methods – Summary Table with Examples & Output

Method Description Example Code Output


get() Get value by key d = {'a': 1}; 1
print(d.get('a'))
print(d.get('z', 'Not Found')) 'Not Found'
keys() Returns all keys d = {'a': 1, 'b': 2}; dict_keys(['a', 'b'])
print(d.keys())
values() Returns all values print(d.values()) dict_values([1, 2])
items() Returns key-value print(d.items()) dict_items([('a', 1),
('b', 2)])
pairs
update() Merges two d = {'a': 1}; {'a': 1, 'b': 2}
d.update({'b': 2});
dictionaries
print(d)
pop() Removes key and d = {'a': 1, 'b': 2}; 1
print(d.pop('a'))
returns value
print(d) {'b': 2}
popitem() Removes last d = {'x': 10, 'y': 20}; ('y', 20) (Python 3.7+)
print(d.popitem())
inserted key-value
pair
setdefault() Sets default if key is d = {'a': 1}; 100
print(d.setdefault('b', 100))
missing
print(d) {'a': 1, 'b': 100}
clear() Empties the d = {'a': 1}; {}
d.clear();
dictionary
print(d)
copy() Returns shallow copy d1 = {'a': 1}; {'a': 1}
d2 = d1.copy();
d2['a'] = 2;
print(d1)
fromkeys() Creates new dict keys = ['a', 'b']; {'a': 0, 'b': 0}
d = dict.fromkeys(keys, 0);
from keys
print(d)

Python Dictionary MCQs

1. Which of the following is the correct way to create a dictionary?


A. dict = {"a" => 1, "b" => 2}
B. dict = ("a": 1, "b": 2)
C. dict = {"a": 1, "b": 2}
D. dict = ["a": 1, "b": 2]
Answer: C
Explanation: Curly braces with key: value pairs are used to define a dictionary.

2. What is the output of:

d = {"a": 1, "b": 2}
print(d["c"])

A. 0
B. None
C. Error
D. "c"
Answer: C
Explanation: Accessing a non-existent key directly raises KeyError.

3. What method returns all keys in a dictionary?


A. all_keys()
B. keys()
C. get_keys()
D. keyset()
Answer: B
4. What does d.get("x", 0) return if key "x" doesn't exist?
A. None
B. 0
C. Error
D. "x"
Answer: B
Explanation: get() returns the default value if key is missing.

5. What does dict.clear() do?


A. Removes a key
B. Deletes dictionary
C. Empties the dictionary
D. Resets all values
Answer: C

6. Which method removes and returns the last inserted item?


A. pop()
B. remove()
C. popitem()
D. delete()
Answer: C

7. What will be the output?

d = {"a": 1}
d["b"] = 2
print(d)

A. {"a": 1}
B. {"a": 1, "b": 2}
C. {"b": 2}
D. Error
Answer: B

8. Which is used to merge two dictionaries?


A. combine()
B. merge()
C. add()
D. update()
Answer: D

9. What is the output?


d = {"a": 1}
print(d.setdefault("a", 5))

A. 5
B. 1
C. None
D. Error
Answer: B
Explanation: Key "a" exists, so original value is returned.

10. What is the type of d.items()?


A. list
B. tuple
C. dict_items
D. set
Answer: C

11. Which function creates a new dict from keys with the same value?
A. fromkeys()
B. dict()
C. make_dict()
D. copy()
Answer: A

12. What happens if you use pop("z") on a missing key without default?
A. Returns None
B. Returns 0
C. Raises KeyError
D. Skips key
Answer: C

13. Which of the following is valid?


A. {[1, 2]: "val"}
B. {{1: 2}: 3}
C. {1: [1, 2]}
D. {(1, 2): [3, 4]}
Answer: D
Explanation: Keys must be immutable (tuple is valid, list is not).

14. What will dict.copy() do?


A. Deep copy
B. Shallow copy
C. Reference copy
D. Reverse dictionary
Answer: B

15. Which is NOT a valid dict method?


A. get()
B. values()
C. insert()
D. popitem()
Answer: C

16. in operator checks for:


A. Key
B. Value
C. Pair
D. Index
Answer: A

17. What is the output?

d = {}
d[0] = "zero"
print(d[0])

A. "zero"
B. 0
C. None
D. Error
Answer: A

18. Which method returns only values in the dictionary?


A. all()
B. keys()
C. values()
D. items()
Answer: C

19. Which one is used to loop through keys and values?


A. for key in d:
B. for key, val in d.items():
C. for val in d.values():
D. for item in d:
Answer: B

20. Choose the correct way to create an empty dictionary:


A. d = []
B. d = ()
C. d = {}
D. d = set()
Answer: C

10 Basic Dictionary Programs

1. Create and print a dictionary


d = {"name": "John", "age": 25}
print(d)

Output: {'name': 'John', 'age': 25}


Simple dictionary creation.

2. Add a key-value pair


d = {"a": 1}
d["b"] = 2
print(d)

Output: {'a': 1, 'b': 2}


Add or update key-value.

3. Check if a key exists


d = {"x": 100}
print("x" in d)

Output: True
Using in operator.

4. Access value using get()


d = {"a": 10}
print(d.get("a")) # 10
print(d.get("b", "N/A")) # N/A

Output: 10, N/A


Safe access with optional default.

5. Print all keys


d = {"a": 1, "b": 2}
print(list(d.keys()))

Output: ['a', 'b']


Extract all keys.

6. Print all values


print(list(d.values()))

Output: [1, 2]
Extract all values.

7. Loop through dictionary


for k, v in d.items():
print(k, v)

Output: a 1, b 2
Iterate key-value pairs.

8. Delete a key using pop()


d = {"a": 1, "b": 2}
d.pop("a")
print(d)

Output: {'b': 2}
Removes key and returns value.

9. Empty a dictionary using clear()


d.clear()
print(d)
Output: {}
Removes all items.

10. Copy a dictionary


d1 = {"a": 1}
d2 = d1.copy()
d2["a"] = 2
print(d1, d2)

Output: {'a': 1} {'a': 2}


Creates shallow copy.

7 Intermediate Dictionary Programs

1. Count word frequency in a string


s = "apple banana apple"
d = {}
for word in s.split():
d[word] = d.get(word, 0) + 1
print(d)

Output: {'apple': 2, 'banana': 1}


Common use-case of counting.

2. Merge two dictionaries


a = {"x": 1}
b = {"y": 2}
a.update(b)
print(a)

Output: {'x': 1, 'y': 2}


Use of update() method.

3. Find maximum value in dictionary


d = {"a": 3, "b": 5, "c": 2}
print(max(d.values()))

Output: 5
Using max() on values.
4. Find key with maximum value
print(max(d, key=d.get))

Output: b
Return key with highest value.

5. Sort dictionary by values


sorted_d = dict(sorted(d.items(), key=lambda x: x[1]))
print(sorted_d)

Output: {'c': 2, 'a': 3, 'b': 5}


Using sorted() with lambda.

6. Build dict from two lists


keys = ['a', 'b']
vals = [1, 2]
d = dict(zip(keys, vals))
print(d)

Output: {'a': 1, 'b': 2}


Use zip() to pair keys and values.

7. Check if all values are unique


d = {'a': 1, 'b': 2, 'c': 3}
print(len(set(d.values())) == len(d))

Output: True
Detect duplicate values.

5 Advanced Dictionary Programs

1. Nested dictionary for student records


students = {
"John": {"math": 90, "science": 85},
"Sara": {"math": 95, "science": 80}
}
print(students["Sara"]["science"])

Output: 80
Accessing nested keys.

2. Invert a dictionary (value ➝ key)


d = {"a": 1, "b": 2}
inv = {v: k for k, v in d.items()}
print(inv)

Output: {1: 'a', 2: 'b'}


Reverse key-value mapping.

3. Group values by first character


names = ["alice", "bob", "adam", "bruce"]
group = {}
for name in names:
key = name[0]
group.setdefault(key, []).append(name)
print(group)

Output: {'a': ['alice', 'adam'], 'b': ['bob', 'bruce']}


Grouping using setdefault().

4. Find common keys in two dictionaries


a = {"x": 1, "y": 2}
b = {"y": 3, "z": 4}
print(set(a.keys()) & set(b.keys()))

Output: {'y'}
Set operations on keys.

5. Flatten a nested dictionary (1 level)


d = {'a': {'x': 1}, 'b': {'y': 2}}
flat = {}
for k1 in d:
for k2 in d[k1]:
flat[k1 + "_" + k2] = d[k1][k2]
print(flat)
Output: {'a_x': 1, 'b_y': 2}
Advanced key renaming and flattening.

10 Basic Dictionary Programs (Beginner-Level)


1. Create dictionary from two lists
keys = ['a', 'b', 'c']
values = [1, 2, 3]
d = dict(zip(keys, values))
print(d)

Output: {'a': 1, 'b': 2, 'c': 3}


Zip lists into dictionary.

2. Check if key exists in dictionary


d = {'x': 10, 'y': 20}
print('y' in d)

Output: True
Using in keyword.

3. Iterate over keys and values


d = {'a': 1, 'b': 2}
for k, v in d.items():
print(k, v)

Output:

css
CopyEdit
a 1
b 2

Using items().

4. Count frequency of characters in string


s = 'banana'
freq = {}
for char in s:
freq[char] = freq.get(char, 0) + 1
print(freq)

Output: {'b': 1, 'a': 3, 'n': 2}


Using get() to count.

5. Add new key-value pair to dictionary


d = {'x': 10}
d['y'] = 20
print(d)

Output: {'x': 10, 'y': 20}


Direct assignment.

6. Use fromkeys() to create dictionary


keys = ['id', 'name']
d = dict.fromkeys(keys, None)
print(d)

Output: {'id': None, 'name': None}


Same default value.

7. Sort dictionary by keys


d = {'b': 2, 'a': 1, 'c': 3}
sorted_d = dict(sorted(d.items()))
print(sorted_d)

Output: {'a': 1, 'b': 2, 'c': 3}


Using sorted().

8. Remove a key using pop()


d = {'x': 10, 'y': 20}
d.pop('x')
print(d)

Output: {'y': 20}


Removes key and returns its value.

9. Copy dictionary
d1 = {'a': 1}
d2 = d1.copy()
d2['a'] = 5
print(d1)

Output: {'a': 1}
Shallow copy prevents change to original.

10. Clear a dictionary


d = {'a': 1}
d.clear()
print(d)

Output: {}
Empties all contents.

7 Intermediate Dictionary Programs


1. Merge two dictionaries (Python 3.9+)
d1 = {'a': 1}
d2 = {'b': 2}
d3 = d1 | d2
print(d3)

Output: {'a': 1, 'b': 2}


Using | operator in Python 3.9+.

2. Swap keys and values


d = {'a': 1, 'b': 2}
swapped = {v: k for k, v in d.items()}
print(swapped)

Output: {1: 'a', 2: 'b'}


Dictionary comprehension.

3. Filter dictionary values > 10


d = {'a': 5, 'b': 15, 'c': 25}
filtered = {k: v for k, v in d.items() if v > 10}
print(filtered)
Output: {'b': 15, 'c': 25}
Conditional filtering.

4. Sum all dictionary values


d = {'a': 10, 'b': 20}
print(sum(d.values()))

Output: 30
Use sum() on values.

5. Find key with maximum value


d = {'a': 10, 'b': 25, 'c': 5}
print(max(d, key=d.get))

Output: 'b'
Key with highest value.

6. Group elements by length


words = ['hi', 'hello', 'go', 'data']
d = {}
for word in words:
d.setdefault(len(word), []).append(word)
print(d)

Output: {2: ['hi', 'go'], 5: ['hello'], 4: ['data']}


Using setdefault().

7. Nested dictionary creation


students = {
1: {'name': 'John', 'age': 20},
2: {'name': 'Jane', 'age': 22}
}
print(students[2]['name'])

Output: Jane
Nested dict access.

5 Advanced Dictionary Programs


1. Invert nested dictionary
d = {'x': {'a': 1}, 'y': {'b': 2}}
inverted = {k2: {k1: v2} for k1, v1 in d.items() for k2, v2 in v1.items()}
print(inverted)

Output: {'a': {'x': 1}, 'b': {'y': 2}}


Deep nesting inversion.

2. Count frequency of words in a sentence


sentence = "hello world hello AI"
words = sentence.split()
freq = {}
for w in words:
freq[w] = freq.get(w, 0) + 1
print(freq)

Output: {'hello': 2, 'world': 1, 'AI': 1}


Classic word counter.

3. Build index of first letter of words


words = ['apple', 'ant', 'ball', 'bat']
index = {}
for word in words:
index.setdefault(word[0], []).append(word)
print(index)

Output: {'a': ['apple', 'ant'], 'b': ['ball', 'bat']}


Grouping by initial letter.

4. Check if two dictionaries are equal


d1 = {'x': 1, 'y': 2}
d2 = {'y': 2, 'x': 1}
print(d1 == d2)

Output: True
Order doesn't matter.

5. Recursive flatten nested dictionary


def flatten(d, parent_key='', sep='_'):
items = {}
for k, v in d.items():
new_key = f"{parent_key}{sep}{k}" if parent_key else k
if isinstance(v, dict):
items.update(flatten(v, new_key, sep))
else:
items[new_key] = v
return items
nested = {'a': {'b': {'c': 1}}, 'd': 2}
print(flatten(nested))

Output: {'a_b_c': 1, 'd': 2}


Recursive key flattening.

Program 1: Student Marks Lookup

Store student marks and display marks based on name using get()

students = {"Alice": 85, "Bob": 92, "Charlie": 78}


name = input("Enter student name: ")
print("Marks:", students.get(name, "Student not found"))

Output:

Enter student name: Bob


Marks: 92

Concept: Safe access using get()

Program 2: Count Word Frequency in Sentence

Count how often each word appears using setdefault()

sentence = "apple banana apple orange banana apple"


words = sentence.split()
freq = {}
for word in words:
freq[word] = freq.setdefault(word, 0) + 1
print(freq)

Output:
{'apple': 3, 'banana': 2, 'orange': 1}
Concept: setdefault() for counting

Program 3: Merge Two Inventories

Combine two product inventories using update()

store1 = {"apple": 50, "banana": 30}


store2 = {"banana": 20, "orange": 40}
store1.update(store2)
print("Updated Inventory:", store1)
Output:
{'apple': 50, 'banana': 20, 'orange': 40}
Concept: update() overwrites duplicates

Program 4: Print All Key-Value Pairs

Use items() to loop through a dictionary

fruits = {"apple": 10, "banana": 5, "mango": 7}


for fruit, qty in fruits.items():
print(f"{fruit}: {qty}")

Output:

apple: 10
banana: 5
mango: 7

Concept: items() unpacking

Program 5: Build Dictionary from Two Lists

Use zip() to create dictionary of names and scores

names = ["Alice", "Bob", "Charlie"]


scores = [88, 92, 75]
result = dict(zip(names, scores))
print(result)

Output:
{'Alice': 88, 'Bob': 92, 'Charlie': 75}
Concept: Dictionary from lists using zip()

Program 6: Remove a Product from Inventory

Use pop() to remove an item

inventory = {"apple": 20, "banana": 15}


item = input("Enter item to remove: ")
qty = inventory.pop(item, None)
if qty:
print(f"{item} removed, quantity was {qty}")
else:
print("Item not found")

Output:

Enter item to remove: apple


apple removed, quantity was 20
Concept: pop() with fallback

Program 7: Product Defaults Using fromkeys()

Create a new product catalog where all have price 0

products = ["pen", "pencil", "eraser"]


catalog = dict.fromkeys(products, 0)
print(catalog)

Output:
{'pen': 0, 'pencil': 0, 'eraser': 0}
Concept: fromkeys() with default value

Program 8: Shallow Copy Test

Compare original and copy using copy()

original = {"math": 90, "science": 95}


copy_dict = original.copy()
copy_dict["math"] = 100
print("Original:", original)
print("Copy:", copy_dict)

Output:

Original: {'math': 90, 'science': 95}


Copy: {'math': 100, 'science': 95}

Concept: copy() is shallow

Program 9: Remove Last Item with popitem()

Simulate LIFO item removal

d = {"a": 1, "b": 2, "c": 3}


print("Before:", d)
last = d.popitem()
print("Popped:", last)
print("After:", d)

Output:

Before: {'a': 1, 'b': 2, 'c': 3}


Popped: ('c', 3)
After: {'a': 1, 'b': 2}

Concept: popitem() removes last


Program 10: Empty a Dictionary

Use clear() method

mydict = {"name": "John", "age": 30}


mydict.clear()
print("After clear:", mydict)

Output:
After clear: {}
Concept: clear() empties the dict

You might also like