python - 最Pythonic的用于从基于字典键的字典列表中选择一个条目?

标签 python python-3.x dictionary list-comprehension

假设我有 AllData,一个嵌套字典列表(假设有数千个条目),但我只寻找一个条目。

AllData = [
    { "EntryA" : {"A Key":"A Value"} },
    { "EntryB" : {"B Key":"B Value"} },
    { "EntryC" : {"C Key":"C Value"} }
]

目前我只是循环遍历它并在找到匹配的 key 后中断。

MyKey = "EntryB"
FoundData = {}
for item in AllData:
    for key,data in item.items():
        if MyKey.lower() == key.lower():
            FoundData = data
            break
print(FoundData)

但是,作为一名 Python 爱好者,我知道有一种更优雅的方法可以做到这一点。我在正确的列表理解技术方面遇到了一些困难,但我正在努力!下面是我能想到的最好的方法,它将这些数据收集在一行中,但我想知道是否有一个更优雅的解决方案来解决这个问题。

MyKey = "EntryB"    
FoundData = [x for x in AllData if str(list(x.items())[0][0]).lower() == MyKey.lower()][0][MyKey]
print(FoundData)

任何见解将不胜感激:)

最佳答案

如果您使用的是 Python 3.8+,您可以组合赋值表达式 (:=) 和 any() (any() 将当找到第一个有效元素时中断):

AllData = [
    { "EntryA" : {"A Key":"A Value"} },
    { "EntryB" : {"B Key":"B Value"} },
    { "EntryC" : {"C Key":"C Value"} }
]

if any((found:=d) for d in AllData if "EntryB" in d):
    print(found)

打印:

{'EntryB': {'B Key': 'B Value'}}

关于python - 最Pythonic的用于从基于字典键的字典列表中选择一个条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62803085/

相关文章:

python - 用Python中的值更新字典列表中所有匹配的键

python - 将列表转换为十六进制字符串的优雅方式

python - 使用 curl 与 Python 请求

python - 需要帮助解析配置数据

python - Pandas 替换不会替换换行符 - 为什么?

c++ - 两次相同的for循环 : one compiles, 另一个没有

python - 如何编写 Perl、Python 或 Ruby 程序来更改 Windows 上另一个进程的内存?

python - 在python3中制作多个目录

python-3.x - Numba 命名元组签名

python - Pyspark reduceByKey 与 (key, Dictionary) 元组