使用字典中的值查找键

时间:2015-08-13 14:46:42

标签: 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
    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   

1 个答案:

答案 0 :(得分:1)

您可以使用生成器表达式将target与dict .items()中的每个值进行比较,然后将其包含在sorted调用中。

如果值是单个整数,则可以使用==

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']

如果值是整数列表,您可以使用in

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']