字典-缩小值并打印属于它的键-Python

字典-缩小值并打印属于它的键-Python,python,dictionary,Python,Dictionary,我正在对一个字典进行排序,并试图通过它来确定food_type中哪个字典键具有相应的水果值。到目前为止,我下面的代码对我影响最大的是: def fruit (food_type): for f in food_type.values(): if f=="fruit" : return(f) fruit ({'apple': 'fruit', 'lettuce': 'veggie', 'banana'

我正在对一个字典进行排序,并试图通过它来确定food_type中哪个字典键具有相应的水果值。到目前为止,我下面的代码对我影响最大的是:

def  fruit (food_type):


         for f in food_type.values():
                if f=="fruit" :
                    return(f)

fruit ({'apple': 'fruit', 'lettuce': 'veggie', 'banana':'fruit'})
这只返回一次水果,所以如果这是我在本例中想要的,我不是100%,因为我的最终目标是将值反射回字典,并返回包含水果的键作为其值。我知道为了得到一个值,你可以做:d[k]或d.getk等等

我正在为此查找以下输出:

["apple","banana"]

您需要遍历键、值对,将匹配项累积到列表中,然后返回该列表

A很好地完成了工作:

def fruit(food_type):
    return [k for k, v in food_type.items() if v == 'fruit']

您需要遍历键、值对,将匹配项累积到列表中,然后返回该列表

A很好地完成了工作:

def fruit(food_type):
    return [k for k, v in food_type.items() if v == 'fruit']

这可能就是你想要的:

def  fruit (food_type):
    return [k for k in food_type if food_type[k] == "fruit"]

print fruit ({'apple': 'fruit', 'lettuce': 'veggie', 'banana':'fruit'})

# ['apple', 'banana']

这可能就是你想要的:

def  fruit (food_type):
    return [k for k in food_type if food_type[k] == "fruit"]

print fruit ({'apple': 'fruit', 'lettuce': 'veggie', 'banana':'fruit'})

# ['apple', 'banana']

下面的代码将返回新字典,其中只包含值等于“fruit”的条目:

>>> d = {'apple': 'fruit', 'lettuce': 'veggie', 'banana':'fruit'}
>>> {k: v for k, v in d.items() if v == 'fruit'}
{'apple': 'fruit', 'banana': 'fruit'}

如果只需要键,只需对其调用keys方法。

下面的代码将返回新字典,其中只包含值等于'fruit'的条目:

>>> d = {'apple': 'fruit', 'lettuce': 'veggie', 'banana':'fruit'}
>>> {k: v for k, v in d.items() if v == 'fruit'}
{'apple': 'fruit', 'banana': 'fruit'}

如果只需要键,只需对其调用keys方法。

您还可以使用以下方法反转字典:

inverse_d = {}
for k, v in d.iter_items():
    if v not in inverse_d:
        inverse_d[v] = [k]
    else :
        inverse_d[v].append(k)
然后

print inverse_d["fruit"]

您还可以使用以下方法反转词典:

inverse_d = {}
for k, v in d.iter_items():
    if v not in inverse_d:
        inverse_d[v] = [k]
    else :
        inverse_d[v].append(k)
然后

print inverse_d["fruit"]

dict.setdefault或collections.defaultdict将不再需要if/else块。我知道。我认为这对初学者来说更容易理解。谢谢你用更简单的术语来表达。我对Python.dict.setdefault或collections.defaultdict相当陌生,它将不再需要if/else块。我知道。我认为这对初学者来说更容易理解。谢谢你用更简单的术语来表达。我对Python相当陌生。