Python中从字典中提取所有值到列表

云课堂学Python 2024-06-27 07:05:14
有时候,在使用 Python 字典时,只关心获取字典的值而不关心字典的键。可以使用多种方法从字典中获取所有的值。 使用 keys() 方法Python 字典(Dictionary) keys() 方法以列表返回一个字典所有的键。使用循环访问每个键的值并将其附加到列表中。 dct = {'A' : 1, 'B' : 2, 'C' : 3}lst = []for key in dct.keys(): lst.append(dct[key])print(lst) # 输出:[1, 2, 3]使用 values() 方法Python 字典(Dictionary) values() 方法以列表返回字典中的所有值。这是获取字典的值的最佳和最直接的方法。 dct = {'A' : 1, 'B' : 2, 'C' : 3}lst = list(dct.values())print(lst)使用 items() 方法Python 字典(Dictionary) items() 方法以列表返回可遍历的(键, 值) 元组数组。然后,使用列表推导式提取字典的值。 dct = {'A' : 1, 'B' : 2, 'C' : 3}lst = [v for k, v in dct.items()]print(lst)使用 * 解包直接使用 “*” 解包字典,返回的是字典的键,结合 values() 方法,获取字典的值。 dct = {'A' : 1, 'B' : 2, 'C' : 3}lst = [*dct.values()]print(lst)使用列表推导式遍历字典的键,输出相应的值。 dct = {'A' : 1, 'B' : 2, 'C' : 3}lst = [dct[i] for i in dct]print(lst)使用 lambda 函数dct = {'A' : 1, 'B' : 2, 'C' : 3}lst = list(map(lambda x: x, dct.values()))print(lst)
0 阅读:4

云课堂学Python

简介:感谢大家的关注