Fundamentals 8 min read

Master Python Dictionaries: Basics, Operations, and Traversal Techniques

This tutorial explains Python dictionaries, covering their definition, key‑value storage, common operations such as adding, deleting, modifying, and clearing elements, as well as traversal methods including keys, values, items, and enumerate, with clear code examples and output screenshots.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Python Dictionaries: Basics, Operations, and Traversal Techniques

1. Introduction

If you need to modify a name in a list, you must use the corresponding index; when the list order changes, you must adjust the index. Dictionaries store multiple pieces of data and let you locate an element directly by its key.

nameList = ['xiaoZhang', 'xiaoWang', 'xiaoLi']
nameList[1] = 'xiaoxiaoWang'

If the list order changes:

nameList = ['xiaoWang', 'xiaoZhang', 'xiaoLi']
nameList[0] = 'xiaoxiaoWang'

Dictionaries solve this problem by using keys instead of numeric indexes.

2. Dictionary Overview

Dictionaries, like lists, can store multiple data items.

List elements are accessed by index.

Dictionary elements are accessed by a key (the part before the colon).

Each element consists of a key and a value, e.g., 'name':'class monitor'.

Example of creating and accessing a dictionary:

info = {'name':'class monitor', 'id':100, 'sex':'f', 'address':'Earth Asia China Beijing'}
print(info['name'])
print(info['address'])

Output:

Accessing a non‑existent key raises a KeyError: info['age'] # raises KeyError Use get to avoid errors and provide a default value:

age = info.get('age')               # returns None
age = info.get('age', 18)           # returns 18 if key is missing
print(age)

2.1 Common Operations – Adding Elements

info = {'name':'class monitor', 'sex':'f', 'address':'Earth Asia China Beijing'}
newId = input('Enter new ID: ')
info['id'] = int(newId)
print('Added id:', info['id'])

Output (example):

2.2 Deleting Elements

Delete a specific key:

print('Before:', info['name'])
del info['name']
print('After:', info.get('name'))

Delete the entire dictionary:

print('Before:', info)
del info
# info is no longer defined

Clear all items:

print('Before clear:', info)
info.clear()
print('After clear:', info)

2.3 Modifying Elements

info = {'name':'class monitor', 'id':100, 'sex':'f', 'address':'Earth Asia China Beijing'}
newId = input('Enter new ID: ')
info['id'] = int(newId)
print('Modified id:', info['id'])

3. Dictionary Utility Functions

len(dict)

– number of key‑value pairs. dict.keys() – list of keys. dict.values() – list of values. dict.items() – list of (key, value) tuples.

mydict = {'name':'alice', 'sex':'f'}
print(len(mydict))
print(mydict.keys())
print(mydict.values())
print(mydict.items())

4. Traversal

Use for ... in ... to iterate over strings, lists, tuples, and dictionaries.

4.1 Iterate Over Keys

for key in info:
    print(key)

4.2 Iterate Over Values

for value in info.values():
    print(value)

4.3 Iterate Over Items

for key, value in info.items():
    print(key, value)

4.4 Enumerate

chars = ['a', 'b', 'c', 'd']
for i, ch in enumerate(chars):
    print(i, ch)

5. Conclusion

This article uses everyday analogies to introduce Python dictionaries, demonstrating basic creation, CRUD operations, utility functions, and traversal techniques with practical code snippets and output screenshots, helping readers deepen their understanding of this fundamental data structure.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonData StructuresCRUDdictionarycoding tutorialTraversal
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.