A Python dictionary is a mutable mapping of unique, hashable keys to values. Dictionaries preserve insertion order, but they are accessed by key, not by numeric position.
Each key is separated from its value by a colon, and key-value pairs are separated by commas:
student = {'name': 'Alex', 'mark': 82}
print(student['name'])AlexUse dictionaries when one value should be looked up by a meaningful key such as an ID, name or code.
Show Table of ContentsCreate an empty dictionary with {} or dict().
my_dict = dict()
print(type(my_dict))<class 'dict'>my_dict = {}
print(type(my_dict))<class 'dict'>Create a dictionary with key-value pairs:
my_dict = {1: 'Alex', 2: 'Ronald'}
print(my_dict){1: 'Alex', 2: 'Ronald'}Keys must be unique. Assigning a new value to an existing key replaces the previous value. Values may be duplicated.
data = {'a': 'Alex', 'b': 'Ronald', 'a': 'Ravi'}
print(data){'a': 'Ravi', 'b': 'Ronald'}Keys must be hashable. Strings, numbers and many tuples can be keys; a list cannot be a key because it is mutable and unhashable.
valid = {('north', 1): 'Zone A'}
print(valid[('north', 1)])Zone Ainvalid = {[1, 2]: 'value'}The last line is syntactically valid but raises TypeError: unhashable type: 'list' at runtime.
| Method | Purpose |
|---|---|
clear() | Remove all items. |
copy() | Create a shallow copy. |
fromkeys() | Create a dictionary from keys with a shared default value. |
get() | Return a value without raising KeyError when the key is absent. |
items() | Return a dynamic view of key-value pairs. |
keys() | Return a dynamic view of keys. |
pop() | Remove a specified key and return its value. |
popitem() | Remove and return the most recently inserted key-value pair. |
setdefault() | Get a key value, inserting a default if the key is absent. |
update() | Add or replace key-value pairs. |
values() | Return a dynamic view of values. |
my_dict = {'a': 'Alex', 'b': 'Ronald'}
print(my_dict['b'])Ronaldget() is useful when a key might be missing:
my_dict = {'a': 'Alex', 'b': 'Ronald'}
print(my_dict.get('a'))
print(my_dict.get('x', 'Not found'))Alex
Not foundA dictionary is not accessed by positional index. In this example, 0 is interpreted as a key and raises KeyError because that key does not exist:
my_dict = {'a': 'Alex', 'b': 'Ronald'}
print(my_dict[0])my_dict = {'a': ['Alex', 30], 'b': ['Ronald', 40], 'c': ['Ronn', 50]}
print(len(my_dict))
print(len(my_dict['a']))3
2my_dict = {'a': 'One', 'b': 'Two', 'c': 'Three'}
values = list(my_dict.values())
print(values)['One', 'Two', 'Three']Iterating over a dictionary directly with a for loop yields keys in insertion order.
my_dict = {'a': 'Alex', 'b': 'Ronald'}
for key in my_dict:
print(key)a
bUse items() when both keys and values are needed:
my_dict = {'a': 'Alex', 'b': 'Ronald'}
for key, value in my_dict.items():
print(key, value)a Alex
b RonaldA membership test checks keys by default. An if condition can act on the result:
my_dict = {'a': 'Alex', 'b': 'Ronald'}
if 'b' in my_dict:
print('Key exists')Key existsTo search values, test the values() view:
my_dict = {'a': 'Alex', 'b': 'Ronald'}
if 'Ronald' in my_dict.values():
print('Value exists')Value existsDictionaries are designed primarily for key-to-value lookup. If reverse lookup is occasionally needed, iterate through items():
my_dict = {'a': 'Alex', 'b': 'Ronald'}
for key, value in my_dict.items():
if value == 'Ronald':
print(key)bThe same pattern can work with list values:
my_dict = {'a': ['Alex', 30], 'b': ['Ronald', 40], 'c': ['Ronn', 50]}
for key, value in my_dict.items():
if value[0] == 'Ronald':
print('Mark:', value[1], 'Key:', key)Mark: 40 Key: bfor key, value in my_dict.items():
if 'Ronn' in value:
print(key, value)c ['Ronn', 50]my_dict = {'a': 'Alex', 'b': 'Ronald'}
my_dict['c'] = 'Ronn'
print(my_dict){'a': 'Alex', 'b': 'Ronald', 'c': 'Ronn'}update() can add new keys and replace existing keys.
my_dict = {'a': 'Alex', 'b': 'Ronald'}
my_dict.update({'b': 'Ravi', 'c': 'John'})
print(my_dict){'a': 'Alex', 'b': 'Ravi', 'c': 'John'}del removes a specified key-value pair:
my_dict = {'a': 'Alex', 'b': 'Ronald', 'c': 'Ronn'}
del my_dict['b']
print(my_dict){'a': 'Alex', 'c': 'Ronn'}Deleting the variable itself removes the dictionary binding:
my_dict = {'a': 'Alex'}
del my_dict
print(my_dict)The final line raises NameError.
For method-based removal, see pop(), popitem() and clear().
my_dict = {'a': 'Alex', 'b': 'Ronald'}
copy_one = dict(my_dict)
copy_two = my_dict.copy()
print(copy_one)
print(copy_two){'a': 'Alex', 'b': 'Ronald'}
{'a': 'Alex', 'b': 'Ronald'}Both are shallow copies. Nested mutable values remain shared unless they are copied separately.
original = {'scores': [10, 20]}
copy_one = original.copy()
copy_one['scores'].append(30)
print(original){'scores': [10, 20, 30]}update() modifies the first dictionary:
d1 = {'a': 'Alex', 'b': 'Ronald', 'c': 'Ronn'}
d2 = {'d': 'Rabi', 'b': 'Kami', 'c': 'Loren'}
d1.update(d2)
print(d1){'a': 'Alex', 'b': 'Kami', 'c': 'Loren', 'd': 'Rabi'}The merge operator | creates a new dictionary:
d1 = {'a': 'Alex', 'b': 'Ronald'}
d2 = {'b': 'Kami', 'c': 'Loren'}
merged = d1 | d2
print(merged){'a': 'Alex', 'b': 'Kami', 'c': 'Loren'}Dictionary unpacking is another way to create a merged dictionary:
merged = {**d1, **d2}
print(merged){'a': 'Alex', 'b': 'Kami', 'c': 'Loren'}students = {
'a': ['Alex', 30],
'b': ['Ronald', 40],
'c': ['Ronn', 50],
}
print(students['a'][0])
print(students['c'][1])
print(students['a'][:2])Alex
50
['Alex', 30]Add another record by assigning a new key or by using update():
students.update({'d': ['Ravi', 60]})
print(students['d'])['Ravi', 60]Like a list comprehension, a dictionary comprehension builds a collection from an expression and iteration.
squares = {number: number ** 2 for number in range(1, 6)}
print(squares){1: 1, 2: 4, 3: 9, 4: 16, 5: 25}max() and min() operate on dictionary keys by default. Apply them to values() when you want the maximum or minimum value.
scores = {'Alex': 72, 'Ravi': 88, 'John': 65}
print(max(scores))
print(min(scores))
print(max(scores.values()))
print(min(scores.values()))Ravi
Alex
88
65The original tutorial used an older SQLAlchemy execution style. Current SQLAlchemy code executes through a connection. See the Python MySQL tutorials and Python with MySQL and SQLAlchemy.
from sqlalchemy import create_engine, text
engine = create_engine('mysql+mysqldb://user:password@localhost/my_tutorial')
with engine.connect() as connection:
rows = connection.execute(
text('SELECT id, name, mark FROM student LIMIT 5')
).mappings()
students = {row['id']: dict(row) for row in rows}
print(students)This preserves the original goal: use the database ID as the dictionary key and store each row as its value.
text_value = 'Welcome to Python'
frequency = {}
for char in text_value:
frequency[char] = frequency.get(char, 0) + 1
print(frequency)get() keeps the counting logic compact. For larger counting tasks, see collections.Counter.
Sample CSV data:
1,Ravi,20,30,40,120
2,Raju,30,40,50,130
3,Alex,40,50,60,140
4,Ronn,50,60,70,150
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.