简单 Python 快乐之旅之:Python 基础语法之字典操作专题


Python 字典允许我们存放键值对。字典中的键值对的顺序是不能保证的,这是因为 Python 的字典并不保存它们的索引。
字典的一个简单示例如下:

myDictionary = {
	"pi": 3.14,
	"phi": 1.618
	}

在这个字典中,pi 和 phi 是键,而 3.14 和 1.618 则是它们相应的值,从而组成了键值对。
在本文中,我们将会学习以下内容:如何创建一个 Python 字典;如何给字典添加和移除元素;循环字典中的元素;以及其他的一些配有示例程序的 Python 字典操作以及转换。

1. Python 字典示例

在 Python 中,字典是由大括号和键值对创建。一个基本的 Python 字典的示例如下:

myDictionary = {
	"Python": "High Level Programming Language",
	"Assembly": "Machine Level Programming Lanugage",
	"SciPy": "Python Library for Mathematical and Scientific Calculations"
	}

其中,myDictionary 变量持有对该字典的引用,你可以使用该变量名来访问字典里的值,也可以调用任意的字段函数。

1.1. 打印字典

你可以使用 print() 函数将字段打印到控制台。字段将被转换为一个字符串常量然后打印出来。

# Python Example – Print Dictionary
myDictionary = {
    "Python" : "High Level Programming Language",
    "Assembly" : "Machine Level Programming Language",
    "SciPy" : "Python Library for Mathematical and Scientific Calculations"
}
print(myDictionary)

执行和输出:
打印字典.png

1.2. 检查对象是否字典类型

你可以使用 type() 函数来检查一个字典变量是否确实是字典类型。

# Python Example – Check if it is Dictionary
print(type(myDictionary))

执行和输出:
检查对象是否字典类型.png

2. 添加元素到字典的例子

要添加元素到现有的一个字典,你可以使用键作为索引将值直接分配给该字典变量。
myDictionary[newKey] = newValue
其中 myDictionary 就是我们要添加键值对 newKey:newValue 的现有索引。

2.1. 添加多个元素到字典

在本示例中,我们将要添加多个元素到字典中去。

# create and initialize a dictionary
myDictionary = {
    'a' : '65',
    'b' : '66',
    'c' : '67'
}
# add new items to the dictionary
myDictionary['d'] = '68'
myDictionary['e'] = '69'
myDictionary['f'] = '70'
print(myDictionary)

执行和输出:
添加多个元素到字典.png

2.2. 添加单个元素到字典

接下来的示例中我们初始化了一个字典,然后将一个键值对的新元素添加给它。

# create and initialize a dictionary
myDictionary = {
"Python" : "High Level Programming Language",
    "Assembly" : "Machine Level Programming Language",
    "SciPy" : "Python Library for Mathematical and Scientific Calculations"
}
# add new item to the dictionary
myDictionary['Matplotlib'] = 'Python library to draw plots'
print(myDictionary)
print(myDictionary['Matplotlib'])

执行和输出:
添加单个元素到字典.png

3. 字典循环遍历

你可以使用 for 循环来遍历一个字典。字典是可以被迭代的,因此我们可以用 for 循环。

# Python Dictionary Loop Example
myDictionary = {
    "Python" : "High Level Programming Language",
    "Assembly" : "Machine Level Programming Language",
    "SciPy" : "Python Library for Mathematical and Scientific Calculations"
}
for item in myDictionary:
    print(item)

执行和输出:
打印出了所有的键元素.png
打印出了所有的键元素。

3.1. 循环遍历字典的键和值

要拿到相关的值的话,你可以使用拿到的键去获取对应的值。

# Loop through keys and values of Dictionary
for key in myDictionary:
    print(key, myDictionary[key], sep=':')
for key, value in myDictionary.items():
    print(key, ':', value)

执行和输出:
循环遍历字典的键和值.png

4. 循环遍历字典的值

有时只需要遍历字典里的值,你可以通过字典变量的 values() 函数来对字典里的值进行单独访问,然后再使用 for 循环对这些值进行遍历。

# Loop through Dictionary Values Example
myDictionary = {
    "Python" : "High Level Programming Language",
    "Assembly" : "Machine Level Programming Language",
    "SciPy" : "Python Library for Mathematical and Scientific Calculations"
}
for value in myDictionary.values():
    print(value)

执行和输出:
循环遍历字典的值.png

4.1. 打印字典的值

字典的 values() 函数返回所有值的一个列表对象。

# Print Dictionary Values
print(myDictionary.values())

执行和输出:
打印字典的值.png

5. 检查键是否存在于字典

要检查一个键是否在一个字典里,可以使用 in 关键字,下边是一个快速示例:
isPresent = ‘Python’ in myDictionary
如果键 Python 存在于该字典,返回 True,否则的话返回 False。
假如字段命名为 myDictionary,在判断给定某键是否存在于该字典时,我们需要同时考虑正向结果 (该键存在) 和负向结果 (该键不存在)。

# Check if Key Exists in Dictionary Example
myDictionary = {
    "Python" : "High Level Programming Language",
    "Assembly" : "Machine Level Programming Language",
    "SciPy" : "Python Library for Mathematical and Scientific Calculations"
}
isPresent = 'Python' in myDictionary
print('Python', 'is present in myDictionary:', isPresent)
isPresent = 'Java' in myDictionary
print('Java', 'is present in myDictionary:', isPresent)

执行和输出:
检查键是否存在于字典.png

6. 获得字典长度

要获得字典的长度或者字典中元素的个数,你可以使用标准库的 len() 函数。获得字典长度的语法如下:
len(myDictionary)
len() 返回的是字典中键值对的个数。

# Dictionary Length Example
myDictionary = {
    "Python" : "High Level Programming Language",
    "Assembly" : "Machine Level Programming Language",
    "SciPy" : "Python Library for Mathematical and Scientific Calculations"
}
length = len(myDictionary)
print('Length of dictionary is', length)

执行和输出:
获得字典长度.png

7. 移除字典里的特定元素

要移除字典里的一个键值对项,使用字典对象的 pop() 函数并将键作为参数传递给它。

myDictionary.pop(theKey)

其中 myDictionary 是一个字典对象,theKey 是你想移除的键值对的键。同时,pop 函数返回的是相对应键值对的值。
此外,你还可以使用 del 关键字通过键来移除某个键值对:

del myDictionary[theKey]

7.1. 使用 pop() 函数来移除元素

在接下来的示例中我们创建了一个字典,初始化以后,使用 pop() 函数将某项移除。

# Example to pop item from Dictionary using pop() function
myDictionary = {
    "Python" : "High Level Programming Language",
    "Assembly" : "Machine Level Programming Language",
    "SciPy" : "Python Library for Mathematical and Scientific Calculations"
}
poppedItem = myDictionary.pop('SciPy')
print(poppedItem)
print(myDictionary)

执行和输出:
使用 pop() 函数来移除元素.png
可以看出,使用 pop() 函数,我们不仅可以将该键值对从字典中移除,而且我们还能将键值对的值存放于一个变量中去。

7.2. 使用 del 关键字将元素移除

接下来我们还创建一个字典,将其初始化,然后是要 del 关键字将某项移除。

# Example to pop item from Dictionary using del keyword
myDictionary = {
    "Python" : "High Level Programming Language",
    "Assembly" : "Machine Level Programming Language",
    "SciPy" : "Python Library for Mathematical and Scientific Calculations"
}
del  myDictionary['SciPy']
print(myDictionary)

执行和输出:
使用 del 关键字将元素移除.png

8. 字典清空

要清空一个字典,也就是说将字典中的所有元素移除,使用字典对象的 clear() 函数。

myDictionary.clear()

8.1. 清空字典的例子

接下来的示例中我们创建了一个字典,将其使用多个键值对元素进行初始化,然后是要 clear() 函数将其清空。

# Example to remove all items in a Python Dictionary
myDictionary = {
    "Python" : "High Level Programming Language",
    "Assembly" : "Machine Level Programming Language",
    "SciPy" : "Python Library for Mathematical and Scientific Calculations"
}
print('Dictionary items:\n', myDictionary)
myDictionary.clear()
print('Dictionary items:\n', myDictionary)

执行和输出:
清空字典的例子.png

参考资料

发布了273 篇原创文章 · 获赞 1324 · 访问量 649万+

猜你喜欢

转载自blog.csdn.net/defonds/article/details/97029044
今日推荐