Python字典是一种可变容器模型,且可存储任意类型对象,字典的每个键值对用冒号 : 分割,每个对之间用逗号 , 分割,整个字典包括在花括号 {} 中,字典的键必须是唯一的,但值则不必。
1、创建字典
创建字典非常简单,只需要为字典的键分配一个值即可。
dict = {'Name': 'Zara', 'Age': 7}
2、访问字典中的值
你可以通过键来访问字典中的值,如下所示:
print("Value for 'Name' is : " + dict['Name'])
3、修改字典
向字典添加新条目,修改或删除已有条目,如下所示:
添加新条目
dict['School'] = "DPS School"
print("Updated Dictionary : " + str(dict))
修改条目
dict['Age'] = 8
print("Updated Age in dictionary : " + str(dict))
删除条目
del dict['School']
print("After deleting school : " + str(dict))
4、遍历字典
你可以使用for循环来遍历字典中的所有项,如下所示:
for x in dict:
print(x)
5、字典的常用方法
Python字典提供了一些常用的方法,如keys()、values()和items()等,用于获取字典中的所有键、所有值或所有的键值对。
获取所有的键
print("All keys in dictionary : " + str(dict.keys()))
获取所有的值
print("All values in dictionary : " + str(dict.values()))
获取所有的键值对
print("All items in dictionary : " + str(dict.items()))
6、字典的合并和比较
你可以使用update()方法来合并两个字典,也可以使用==运算符来比较两个字典是否相等。
dict1 = {'Name': 'Zara', 'Age': 7}
dict2 = {'Age': 8, 'School': 'DPS School'}
dict1.update(dict2) # 合并两个字典
print("Updated dictionary : " + str(dict1))
比较两个字典是否相等
if dict1 == dict2:
print("Both dictionaries are equal")
else:
print("Both dictionaries are not equal")
7、字典的排序和查找
你可以使用sorted()函数来对字典进行排序,也可以使用in关键字来查找字典中是否存在某个键或值。
对字典进行排序并打印结果
print("Sorted dictionary by key : " + str(sorted(dict)))
print("Sorted dictionary by value : " + str(sorted(dict, key=dict.get)))
以上就是Python字典的基本概念和使用方法,通过这些内容,你应该能够更好地理解和使用Python字典。



还没有评论,来说两句吧...