gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:18:20 26 4
gpt4 key购买 nike

我有一个 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() :

Retrieve the next item from the iterator by calling its next() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.

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"

关于python - 使用 Python 列表理解从嵌套元组字典结构中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18979442/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com