前面我们简单介绍了Python字典和Python获取字典值。今天我们来聊聊如何遍历python字典。我们还是以car为例子。下面简单介绍三种方法来遍历字典。 1. 使用 for 循环遍历字典。 car = {"brand": "Porsche", "model": "911", "year": 1963}
for x in car: print(x, ":", car[x]) 会得到如下结果 brand : Porsche model : 911 year : 1963 2. 在python里面可以使用 keys()和values() 函数返回字典里所有的keys和所有values。 car = {"brand": "Porsche", "model": "911", "year": 1963} keys = car.keys() values = car.values()
print("Keys:") print(keys) print(len(keys))
print("Values:") print(values) print(len(values)) 会得到如下结果 Keys: dict_keys(['brand', 'model', 'year']) 3 Values: dict_values(['Porsche', '911', 1963]) 3 所有下面的方法也可以遍历整个字典 car = {"brand": "Porsche", "model": "911", "year": 1963}
for x in car.keys(): print(x, ":", car[x]) car = {"brand": "Porsche", "model": "911", "year": 1963} for x, y in car.items(): print(x, ":", y) 下面这种方法是等价的,实际上通过items()函数可以获取所有的键-值对,所以for循环读取carItems,每次取出一个键-值对。key会存放在carItem[0]中,而value会存放在ca[1]中。 car = {"brand": "Porsche", "model": "911", "year": 1963} carItems = car.items() for carItem in carItems: print(carItem[0], ":", carItem[1]) |
|