Python Basics: Creating and Updating Dictionaries, Strings, and Lists
This tutorial explains why lists can be limiting for storing multiple data items, introduces dictionary syntax, and walks through creating, accessing, modifying, adding, and deleting dictionary entries with concrete code examples and their output.
Why Use Dictionaries Instead of Lists
When storing multiple pieces of data in a list, retrieving or modifying specific items can be cumbersome; dictionaries provide a key‑value mapping that solves these shortcomings.
Dictionary Syntax
A dictionary is defined with curly braces using the form {key:value, key1:value1, ...}.
Code Demonstration
list1 = ['张三', 32, 175, "男", "清华大学", "算法工程师"]
dict1 = {"name":"张三", "age":32, "height":175, "sex":"男", "school":"清华大学", "job":"算法工程师"}
print(dict1)
# Access elements
print(dict1['name'])
print(dict1['job'])
# Using get()
print(dict1.get(''))
print(dict1.get('money')) # None when the key does not exist
# Modify an element
dict1['name'] = "张大锤"
print(dict1)
# Add a new element
dict1['money'] = 55000
print(dict1)
# Delete elements
# 1) pop('key')
dict1.pop('school')
print(dict1)
# 2) popitem() removes the last key‑value pair
dict1.popitem()
print(dict1)
# 3) clear() empties the dictionary
dict1.clear()
print(dict1) # {}Output Results
{'name':'张三','age':32,'height':175,'sex':'男','school':'清华大学','job':'算法工程师'}
张三
算法工程师
张三
None
{'name':'张大锤','age':32,'height':175,'sex':'男','school':'清华大学','job':'算法工程师'}The example demonstrates how dictionaries simplify data access and manipulation compared with lists, showing creation, element retrieval via indexing and get(), updating values, adding new keys, and three ways to delete entries.
Lisa Notes
Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
