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

标签 python dictionary tuples list-comprehension

我有一个 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/

相关文章:

python - 如何从输出中删除空格但保留 python 中的字典值?

c++ - 嵌套类中的构造函数 (C++)

python - 将具有相同值的元组组合到列表中

c# - 在 C# 元组中使用 Int64

python - 将字符串拆分为元组列表?

python - PyOpenGL 使用 cx_Freeze 卡住后引发异常?

python - 如何处理我的login_required url?

java - 使用 Java 8 Streams、map、filter、reduce 查找具有名字和姓氏的 Actor 曾工作过的电影

python - 没有名为 'mlxtend' 的模块

python - 使用 zoomed_inset_axes 截断框