Python Dictionary: Keys, Values, Methods and Examples

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'])
Alex

Use dictionaries when one value should be looked up by a meaningful key such as an ID, name or code.


Creating a Dictionary Top ↑

Create 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'}

Dictionary Keys, Values and Insertion Order Top ↑

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 A
invalid = {[1, 2]: 'value'}

The last line is syntactically valid but raises TypeError: unhashable type: 'list' at runtime.

Python Dictionary: Create and Modify Key-Value Pairs

Dictionary Methods Top ↑

MethodPurpose
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.

Accessing Values by Key Top ↑

my_dict = {'a': 'Alex', 'b': 'Ronald'}
print(my_dict['b'])
Ronald

get() 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 found

A 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])

Length of the dictionary and nested values

my_dict = {'a': ['Alex', 30], 'b': ['Ronald', 40], 'c': ['Ronn', 50]}
print(len(my_dict))
print(len(my_dict['a']))
3
2

Create a list from dictionary values

my_dict = {'a': 'One', 'b': 'Two', 'c': 'Three'}
values = list(my_dict.values())
print(values)
['One', 'Two', 'Three']

Looping and Membership Tests Top ↑

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
b

Use 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 Ronald

A 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 exists

To search values, test the values() view:

my_dict = {'a': 'Alex', 'b': 'Ronald'}
if 'Ronald' in my_dict.values():
    print('Value exists')
Value exists

Find a key from a value

Dictionaries 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)
b

The 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: b
for key, value in my_dict.items():
    if 'Ronn' in value:
        print(key, value)
c ['Ronn', 50]

Add and Update Items Top ↑

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'}

Remove Items Top ↑

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().

Copying a Dictionary Top ↑

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]}

Merging Dictionaries Top ↑

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'}

Dictionary Containing Lists and Nested Data Top ↑

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]

Dictionary Comprehension Top ↑

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}

Maximum and minimum keys or values

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
65

Create a Dictionary from Database Rows Top ↑

The 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.

Count Character Frequency with a Dictionary Top ↑

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.

Dictionary Exercises Top ↑

  1. Ask for the name and mark of three students, create a dictionary and print it.
  2. Store three students where the student name is the key and the value contains Physics, Chemistry, Math and attendance data. Print every student name and attendance.
  3. Read CSV rows where the first column is an ID and build a dictionary using the ID as the key.

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

Dictionary exercise solutions




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer