创建词典
字典使用花括号 {} 创建,由冒号 : 分隔的键值对组成
# Example of a dictionary
person = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
# output will be {'name': 'John Doe', 'age': 30, 'city': 'New York'}py
在这个例子中, "name" 、 "age" 和 "city" 是键,每个键与相应的值相关联。
字典是一个有序的、可改变的、不允许重复的集合。
# Example of a dictionary
person = {
"name": "John Doe",
"age": 30,
"city": "New York",
"city": "Washington"
}
# output will be {'name': 'John Doe', 'age': 30, 'city': 'Washington'}
键值读取
可以使用方括号 [] 和键本身访问特定键的值。
person = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
# Accessing values
name = person["name"] # Output: "John Doe"
age = person["age"] # Output: 30
也可以使用 get() 函数来获取值。
name = person.get("name")
修改字典
字典是可变的,这意味着您可以更改与键关联的值。
# Modifying values
person["age"] = 31
# using update function
person.update({"age":45})
添加新条目
可以向字典中添加新的键值对。
# Adding a new entry
person["email"] = "john.doe@example.com"
字典方法
字典带有各种用于执行操作的内置方法。一些常用的方法包括 keys() 、 values() 和 items() 。
# Getting keys, values, and items
keys = person.keys() # Output: dict_keys(['name', 'age', 'city', 'email'])
values = person.values() # Output: dict_values(['John Doe', 31, 'New York', 'john.doe@example.com'])
items = person.items() # Output: dict_items([('name', 'John Doe'), ('age', 31), ('city', 'New York'), ('email', 'john.doe@example.com')])
删除条目
可以使用 pop() 、 popitem() 、 clear() 和 del 方法从字典中删除键值对。
# Removing an entry using pop()
city = person.pop("city") # city is "New York", person no longer contains "city" key
# Removing an entry using popitem()
key, value = person.popitem() # Removes and returns the last key-value pair (key = 'city', value = 'New York')# Removing an entry using clear()
person.clear() # Removes all items from 'person' (person is now an empty dictionary)# Removing an entry using clear()
del person["age"], person["city"] # Removes both 'age' and 'city' keys and their associated values
排序字典
字典本质上是无序的,但如果需要,您可以根据键或值对它们进行排序。要对字典进行排序,可以使用带key参数的 sorted() 函数。
按键排序:
person = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
sorted_dict_by_keys = dict(sorted(person.items()))
print(sorted_dict_by_keys)
按值排序:
person = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
sorted_dict_by_values = dict(sorted(person.items(), key=lambda item: item[1]))
print(sorted_dict_by_values)
循环使用字典
通过字典循环,您可以访问它的键和值以进行各种操作。有几种方法可以实现这一点:
循环键:你可以使用 for 循环来循环字典的键。
person = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
for key in person:
print(key)
循环遍历值:您可以使用 values() 方法循环遍历字典的值。
person = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
for value in person.values():
print(value)
同时循环键和值:您可以使用 items() 方法同时循环键和值。
person = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
for key, value in person.items():
print(f"{key}: {value}")
嵌套字典
嵌套字典是包含其他字典作为其值的字典。这允许更复杂的数据结构。
students = {
"student1": {
"name": "John Doe",
"age": 20,
"major": "Computer Science"
},
"student2": {
"name": "Jane Doe",
"age": 21,
"major": "Mathematics"
}
}
可以通过链接键来访问嵌套字典中的值:
print(students["student1"]["name"]) # Output: John Doe