What is a dictionary?#
A dictionary (dict) stores data as key: value pairs. Instead of finding items by position (like lists), you find them by a meaningful key.
student = {
"name": "Asha",
"age": 20,
"course": "Python",
"marks": [85, 90, 78],
}
Think of a real dictionary: you look up a word (key) to get its meaning (value). Or a phone contact list: name → number.
Dictionary में data "key : value" जोड़ियों में रखा जाता है - जैसे फ़ोन की contact list में नाम → नंबर।
List में आप किसी चीज़ तक उसकी position (0, 1, 2...) से पहुँचते हैं, लेकिन dictionary में उसके नाम (key) से - जैसे student["name"]। यह ज़्यादा समझने में आसान है, क्योंकि आपको याद नहीं रखना पड़ता कि name किस position पर था।
Keys unique होती हैं (एक ही key दो बार नहीं हो सकती) और immutable होनी चाहिए (string, number, tuple)। Values कुछ भी हो सकती हैं - list, दूसरी dictionary, कुछ भी।
Properties:
- Keys are unique - a repeated key overwrites the old value.
- Keys must be immutable: strings, numbers, tuples.
- Values can be anything - numbers, lists, other dicts.
- Dictionaries keep insertion order (Python 3.7+) and are mutable.
Accessing values#
student["city"] raises KeyError: 'city' when the key doesn't exist. Use .get() when a key might be missing, or check with if "city" in student: first.
Adding and updating#
The same syntax adds a new key or updates an existing one:
Removing#
| Code | What it does |
|---|---|
del d[key] |
delete a key (KeyError if missing) |
d.pop(key) |
remove and return its value |
d.pop(key, default) |
same, but no error if missing |
d.popitem() |
remove and return the last inserted pair |
d.clear() |
empty the dictionary |
Looping over a dictionary#
keys(), values(), items()#
marks.keys() # dict_keys(['Maths', 'Science', 'English'])
marks.values() # dict_values([92, 85, 78])
marks.items() # dict_items([('Maths', 92), ('Science', 85), ('English', 78)])
Wrap them in list() if you need an actual list.
Checking keys#
if "Maths" in marks: # checks KEYS, not values
print("Maths marks found")
if 92 in marks.values(): # check values explicitly
print("Someone got 92")
Counting with a dictionary - a very common pattern#
count[v] = count.get(v, 0) + 1 - इस लाइन को ध्यान से समझें, यह बहुत काम आती है:
count.get(v, 0)- अगरvपहले से dictionary में है तो उसकी गिनती दो, वरना 0 दो।- उसमें
+ 1जोड़ो। - नई गिनती वापस
count[v]में रख दो।
यानी पहली बार कोई चीज़ मिली तो गिनती 1 हो जाएगी, दूसरी बार 2, और ऐसे ही आगे।
Python also has collections.Counter which does this in one line: Counter(votes). You'll meet it in the Modules lesson.
Nested dictionaries#
Real data (like JSON from websites and APIs) is usually nested:
List of dictionaries - a table of records#
(lambda is explained in the Lambda lesson - here it just tells sorted to compare by salary.)
Other ways to create dictionaries#
d1 = dict(name="Ravi", age=21)
d2 = dict(zip(["a", "b", "c"], [1, 2, 3])) # {'a': 1, 'b': 2, 'c': 3}
d3 = dict.fromkeys(["x", "y"], 0) # {'x': 0, 'y': 0}
squares = {n: n * n for n in range(1, 6)} # dict comprehension
merged = d1 | {"city": "Indore"} # merge (Python 3.9+)
Dictionary methods - quick reference#
| Method | Purpose |
|---|---|
get(k, default) |
safe read |
keys(), values(), items() |
views for looping |
update(other) |
add/overwrite many pairs |
pop(k[, default]) |
remove and return a value |
popitem() |
remove last pair |
setdefault(k, v) |
get k; if missing, insert k with v |
copy() |
shallow copy |
clear() |
remove all |
Summary#
- Dictionaries map unique, immutable keys to values:
{"key": value}. - Read with
d[key](KeyError if missing) ord.get(key, default). d[key] = valueadds or updates;del,popremove.- Loop with
.keys(),.values(),.items(). d.get(k, 0) + 1is the standard counting pattern; nested dicts model real-world data.