使用 Python 列表理解从嵌套元组字典结构中检索数据



我有一个n元组的字典。 我想从这个元组中检索一个包含特定键值对的字典。

我试图尽可能优雅地做到这一点,我认为列表理解是要走的路 - 但这不是基本的列表理解,我有点迷茫。

这显示了我正在尝试做什么的想法,但它当然不起作用:

# 'data' is my n-tuple
# 'myKey' is the key I want
# 'myValue is the value I want
result = [data[x] for dictionary in data if (data[x][myKey]) == myValue)][0]
# which gives this error:
NameError: global name 'x' is not defined
之前,我

尝试过这样的事情(错误是有道理的,我理解它):

result = [data[x] for x in data if (data[x][myKey] == myValue)][0]
# which gives this error:
TypeError: tuple indices must be integers, not dict

现在是使用嵌套推导的时候了吗? 那会是什么样子,到那时用循环和条件写出来会更简单吗?

另外,附带问题 - 除了在末尾拍打 [0] 之外,是否有一种更 pythonic 的方式来获取列表中的第一个(或唯一)元素?

最pythonic的方式是使用next()

通过调用迭代器的 next() 方法从迭代器检索下一项。 如果给出默认值,则在迭代器耗尽时返回, 否则将引发停止迭代。

data = ({'1': 'test1'}, {'2': 'test2'}, {'3': 'test3'})
myKey = '2'
myValue = 'test2'
print next(x for x in data if x.get(myKey) == myValue)  # prints {'2': 'test2'}

您还可以指定默认值,以防找不到该项目:

myKey = 'illegal_key'
myValue = 'illegal_value'
print next((x for x in data if x.get(myKey) == myValue), 
           'No item found')  # prints "No item found"

如果你有一个名为data的字典元组,你可以这样做:

>>> data = ({'fruit': 'orange', 'vegetable':'lettuce'}, {'football':'arsenal', 'basketball':'lakers'}, {'england':'london', 'france':'paris'} )
>>> myKey = "football"
>>> myValue = "arsenal"
>>> [d for d in data if (myKey, myValue) in d.items()][0]
 {'basketball': 'lakers', 'football': 'arsenal'}

这将返回元组中包含myKey的第一个字典,并使用列表推导式myValue(删除 [0] 以获取所有字典)。

但为什么是下一个呢?只需使用生成器。我会这样做(从 alecxe 稍微更改了代码):

data = ({'1': 'test1'}, {'2': 'test2'}, {'3': 'test3'})
myKey = '2'
myValue = 'test2'
result = [data[x] for x in data if data[x] == myValue]

最新更新