Python字典

字典

字典是一个无序、可变和有索引的集合。在 Python 中,字典用花括号编写,拥有键和值。

字典的创建和删除

创建并打印字典

thisdict =	{
  "name": "tom",
  "height": "168",
  "year": 2000
}
print(thisdict)

删除字典

del 关键字可以完全删除字典:

thisdict =	{
  "name": "tom",
  "height": "168",
  "year": 2000
}
del thisdict

print(thisdict) #this 会导致错误,因为 "thisdict" 不再存在。

访问字典

访问元素

您可以通过在方括号内引用其键名来访问字典的项目:
实例

获取 “height” 键的值:

x = thisdict["height"]

get() 的方法会给你相同的结果:
实例

获取 “height” 键的值:

x = thisdict.get("height")

遍历字典

您可以使用 for 循环遍历字典。

循环遍历字典时,返回值是字典的键,但也有返回值的方法。
实例

逐个打印字典中的所有键名:

for x in thisdict:
  print(x)

实例

逐个打印字典中的所有值:

for x in thisdict:
  print(thisdict[x])

实例

您还可以使用 values() 函数返回字典的值:

for x in thisdict.values():
  print(x)

实例

通过使用 items() 函数遍历键和值:

for x, y in thisdict.items():
  print(x, y)

检查键是否存在

要确定字典中是否存在指定的键,请使用 in 关键字:
实例

检查字典中是否存在 “model”:

thisdict =	{
  "name": "tom",
  "height": "168",
  "year": 2000
}
if "height" in thisdict:
  print("Yes, 'height' is one of the keys in the thisdict dictionary")

添加,删除和修改字典中的元素

添加

通过使用新的索引键并为其赋值,可以将项目添加到字典中:
实例

thisdict =	{
  "name": "tom",
  "height": "168",
  "year": 2000
}
thisdict["age"] = "18"
print(thisdict)

删除

有几种方法可以从字典中删除项目:
实例

pop() 方法删除具有指定键名的项:

thisdict =	{
  "name": "tom",
  "height": "168",
  "year": 2000
}
thisdict.pop("height")
print(thisdict)

popitem() 方法删除最后插入的项目(在 3.7 之前的版本中,删除随机项目):

thisdict =	{
  "name": "tom",
  "height": "168",
  "year": 2000
}
thisdict.popitem()
print(thisdict)

实例

del 关键字删除具有指定键名的项目:

thisdict =	{
  "name": "tom",
  "height": "168",
  "year": 2000
}
del thisdict["height"]
print(thisdict)

clear() 关键字清空字典:

thisdict =	{
  "name": "tom",
  "height": "168",
  "year": 2000
}
thisdict.clear()
print(thisdict)

字典方法

Python字典_第1张图片

你可能感兴趣的:(Python入门基础,python,开发语言)