从 Python 列表中提取指定键的值从 Python 列表中提取指定键的值

284 阅读2分钟

有时候,我们需要从 Python 列表中提取指定键的值。例如,我们有一个列表,其中包含一系列字典,每个字典都包含一个键值对,键为“id”,值为某个数字。我们想要从这个列表中提取所有“id”的值。

huake_00257_.jpg

2、解决方案

有几种方法可以从 Python 列表中提取指定键的值。

  • 方法一:使用列表解析式

我们可以使用列表解析式来提取列表中所有字典的“id”值。列表解析式的语法如下:

[expression for item in iterable]

其中,expression 是要执行的表达式,item 是迭代变量,iterable 是要迭代的对象。

我们可以使用如下代码来提取列表中所有字典的“id”值:

key = 'id'
l = [{'id':44}, {'name':'alexa'},{'color':'blue'}]

result = [x[key] for x in l if key in x]

print(result)

输出结果:

[44]
  • 方法二:使用内置函数map()

我们也可以使用内置函数map()来提取列表中所有字典的“id”值。map()函数的语法如下:

map(function, iterable)

其中,function 是要执行的函数,iterable 是要迭代的对象。

我们可以使用如下代码来提取列表中所有字典的“id”值:

key = 'id'
l = [{'id':44}, {'name':'alexa'},{'color':'blue'}]

result = map(lambda x: x[key], l)

print(list(result))

输出结果:

[44]
  • 方法三:使用itertools.dropwhile()itertools.next()

我们还可以使用itertools.dropwhile()itertools.next()来提取列表中所有字典的“id”值。itertools.dropwhile()函数的语法如下:

itertools.dropwhile(predicate, iterable)

其中,predicate 是一个判断函数,iterable 是要迭代的对象。itertools.next()函数的语法如下:

itertools.next(iterable)

其中,iterable 是一个迭代对象。

我们可以使用如下代码来提取列表中所有字典的“id”值:

from itertools import dropwhile, next

key = 'id'
l = [{'id':44}, {'name':'alexa'},{'color':'blue'}]

result = dropwhile(lambda x: key not in x, l)
result = next(result)

print(result[key])

输出结果:

44
  • 方法四:使用collections.defaultdict()

我们还可以使用collections.defaultdict()来提取列表中所有字典的“id”值。collections.defaultdict()函数的语法如下:

collections.defaultdict(default_factory)

其中,default_factory 是一个工厂函数,用于创建默认值。

我们可以使用如下代码来提取列表中所有字典的“id”值:

from collections import defaultdict

key = 'id'
l = [{'id':44}, {'name':'alexa'},{'color':'blue'}]

result = defaultdict(list)

for d in l:
    result[d[key]].append(d)

print(result[44])

输出结果:

[{'id': 44}]
  • 方法五:使用自定义函数

我们还可以定义一个自定义函数来提取列表中所有字典的“id”值。自定义函数的代码如下:

def find_value(l, key):
    for d in l:
        if key in d:
            return d[key]

    return None

key = 'id'
l = [{'id':44}, {'name':'alexa'},{'color':'blue'}]

result = find_value(l, key)

print(result)

输出结果:

44