Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如果没有if语句,如何查找dict中存在的键?_Python_Python 3.x - Fatal编程技术网

Python 如果没有if语句,如何查找dict中存在的键?

Python 如果没有if语句,如何查找dict中存在的键?,python,python-3.x,Python,Python 3.x,我有一本字典,知道那本字典里只有N个键中的一个。任务是查找并保存现有密钥的值 我编写了以下bruteforce代码,但我相信应该有一个很好的oneliner或其他东西: final_key = None for key in ['aa', 'bbb', 'cccc', 'ddddd', 'e']: if key in dict: final_key = key break 您可以尝试以下方法: next(x in your_list if x in dict)

我有一本字典,知道那本字典里只有N个键中的一个。任务是查找并保存现有密钥的值

我编写了以下bruteforce代码,但我相信应该有一个很好的oneliner或其他东西:

final_key = None
for key in ['aa', 'bbb', 'cccc', 'ddddd', 'e']:
   if key in dict:
      final_key = key
      break

您可以尝试以下方法:

next(x in your_list if x in dict)

它会生成一个迭代器,只会找到其中的第一个元素。

您可以通过一个集合操作来完成:

set(dict).intersection(['aa', 'bbb', 'cccc', 'ddddd', 'e'])

您还可以使用
filter
get
方法查找字典的键:

final_key = list(filter(lambda key: not dict.get(key,None) is None, ['aa', 'bbb', 'cccc', 'ddddd', 'e']))[0]

注意:您不应该使用
dict
作为变量名,因为它是一个保留的Python关键字。

是否使用if语句?请尝试以下操作:

i = 0
while yourlist[i] not in yourdict: i+=1
final_key = yourlist[i]

该代码段迭代字典键,并返回包含在给定列表中的键

next(
   x for x in
   dictionary.keys()
   if x in ['aa', 'bbb', 'cccc', 'ddddd', 'e']
)

只是为了完成答案,这绝对不是一个好方法

试试看:
dict[键]
除KeyError外:
打印(“密钥不存在”)

在python3中非常简单

dict.__contains__('your key here')
在python2中

dict.has_key('your key here')
它将为您提供True或False值

一行代码,而不使用if语句。 考虑一个传统的、有文档记录的、干净的功能:

def find_first(candidates, collection):
  """Find the first element of candidates also in collection"""
  for k in candidates:
    if k in collection: return k
  return None # or raise a KeyNotFound exception!
或一些(未经测试的)单层衬里,例如:

next(set(candidates).intersection(set(collection))

您希望在一年内调试哪些代码?如果速度太慢,您更希望优化哪一个(一行程序可能要慢好几倍)。

更简洁:
set(dict)。intersection…
。但是要注意
dict
的用法。但是那里有一个
if
。但是那里有一个
if
。为什么没有
if
语句?只需将其命名为一个函数,无需将所有内容都设置为一行(这可能会以效率为代价)。我更喜欢这种直截了当的代码(它甚至会更简单,因为你可以在适当的函数中执行
if-key-in-dict:return-key
。你仍然需要
if
和一个循环来使用它们。它与
key-in-dict
语句没有什么不同。