Python 在字典中查找具有值的键
我正在尝试编写一个Python函数,返回Python 在字典中查找具有值的键,python,python-2.7,Python,Python 2.7,我正在尝试编写一个Python函数,返回aDict中的键列表,其值为target。键列表应按递增顺序排序。aDict中的键和值都是整数。(如果aDict不包含target值,程序应返回空列表。)键为a、b、c。我收到一条错误消息,上面说没有定义名称“a”。不知道为什么,因为我已经声明a,b和c为整数 def keysWithValue(aDict, target): ''' aDict: a dictionary target: integer a:integer
aDict
中的键列表,其值为target
。键列表应按递增顺序排序。aDict
中的键和值都是整数。(如果aDict
不包含target
值,程序应返回空列表。)键为a、b、c。我收到一条错误消息,上面说没有定义名称“a”。不知道为什么,因为我已经声明a,b和c为整数
def keysWithValue(aDict, target):
'''
aDict: a dictionary
target: integer
a:integer
b:integer
c:integer
'''
# Your code here
i=0
j=0
if aDict[i]==5:
list[j]=aDict[i]
i+=1
j+=1
return list
您可以使用生成器表达式将您的
目标
与dict的.items()
中的每个值进行比较,然后将其包装在排序的
调用中
如果该值是单个整数,则可以使用==
def keysWithValue(aDict, target):
return sorted(key for key, value in aDict.items() if target == value)
>>> d = {'b': 1, 'c': 2, 'a': 1, 'd': 1}
>>> keysWithValue(d, 1)
['a', 'b', 'd']
或者,如果值是整数列表,则可以在
def keysWithValue(aDict, target):
return sorted(key for key, value in aDict.items() if target in value)
>>> d = {'b': [1,2,3], 'c': [2,5,3], 'a': [1,5,7], 'd': [9,1,4]}
>>> keysWithValue(d, 1)
['a', 'b', 'd']
这不是Python中变量的工作方式。OP声明“aDict中的键和值都是整数”。