简体   繁体   English

我如何将 append 与所需值相对应的键添加到 Python 中的列表?

[英]How do I append a key that corresponds with a wanted value to a list in Python?

I have a dictionary that has, for example, {1: apple, 2:orange, 3:pear, 4:apple, etc.} where the value 'apple' is repeated for different key integers (such as the keys 1, 4, 7, 9, and 21 all have the value apple in my dictionary).我有一个字典,例如 {1: apple, 2:orange, 3:pear, 4:apple, etc.} 其中值 'apple' 重复不同的键整数(例如键 1、4 , 7, 9, 和 21 在我的字典中都有值 apple)。 I have a loop that searches the dictionary for the value 'apple', but I want the keys (1, 4, 7, 9, 21, etc.) associated with the value to be appended to a new list called "Apple Numbers" (and just the keys, not the value 'apple').我有一个循环在字典中搜索值“apple”,但我希望将与该值关联的键(1、4、7、9、21 等)附加到名为“Apple Numbers”的新列表中(只有键,而不是值“apple”)。 However, I do not know how to do this.但是,我不知道该怎么做。

I am a beginner, so my apologies for such a basic question.我是初学者,所以对于这样一个基本问题我深表歉意。 Also, this is just an example as this is not the actual problem I need help solving with apples and fruits;另外,这只是一个例子,因为这不是我需要用苹果和水果帮助解决的实际问题; I just need help understanding the concept of how to do this so I can apply it to the project I am working on!我只需要帮助理解如何做到这一点的概念,这样我就可以将它应用到我正在从事的项目中!

Thanks in advance: :)提前致谢: :)

The basic gist is基本要点是

my_apples = []
for key, value in dictionary.items():
    if value == "apple":
        my_apples.append(key)

A more fluent approach would be to use a comprehension:更流畅的方法是使用理解:

my_apples = [key for key, value in dictionary.items() if value == "apple"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM