我可以一次检查字典中的所有值吗?

时间:2014-07-22 19:41:30

标签: python if-statement dictionary

看着我的代码......

# 1 = in the bookshelf, 0 = not in the bookshelf
bookshelf = {}
bookshelf["The Incredible Book About Pillows"] = 1
bookshelf["Little Fox and his Friends"] = 1
bookshelf["How To Become a Superhero: Part 1"] = 0

if bookshelf["The Incredible Book About Pillows"] == 1:
    print("The Incredible Book about Pillows")
if bookshelf["Little Fox and his Friends"] == 1:
    print("Little Fox and his Friends")
if bookshelf["How To Become a Superhero: Part 1"] == 1:
    print("How To Become a Superhero: Part 1")

...有没有更好的方法来打印目前书架上的所有书籍(有价值1)?或者,当我将它们从书架中取出并在我放回书架时添加它们时,这是简单地从字典中删除它们的最简单方法吗?

5 个答案:

答案 0 :(得分:2)

您可以非常轻松地迭代字典的项目:

for key, value in bookshelf.items():   #.iteritems() also works, returns an iterator.
  if value == 1:
    print key

.items()将返回(key, value)元组列表供您仔细阅读和检查。

答案 1 :(得分:2)

使用列表理解:

booksInShelf = [book for book in bookshelf if bookshelf[book] == 1]
for book in booksInShelf:
    print(book)

答案 2 :(得分:0)

您有两种选择。

1)您可以使用字典的键属性来查看字典中是否包含键(书名)。 dict documentation有更多有用的信息。

2)您可以使用列表推导将列表过滤到另一个列表中,该列表中只包含“== 1”的书名

答案 3 :(得分:0)

为什么不这样做:

for book in bookshelf.keys():
    if bookshelf[book] == 1:
        print book

答案 4 :(得分:0)

filter(lambda k: k if bookshelf[k] == 1 else None, bookshelf)