python - 仅打印奇数字典键及其项

标签 python

我有以下字典,我只需要打印奇数(1、3 ...)的字典。我该怎么做呢?

zen = {
    1: 'Beautiful is better than ugly.',
    2: 'Explicit is better than implicit.',
    3: 'Simple is better than complex.',
    4: 'Complex is better than complicated.',
    5: 'Flat is better than nested.',
    6: 'Sparse is better than dense.',
    7: 'Readability counts.',
    8: 'Special cases aren't special enough to the rules.',
    9: 'Although practicality beats purity.',
   10: 'Errors should never pass silently.'
   }

到目前为止我有:

for c in zen:
print (c , zen[c][:])

最佳答案

如果你的键是数字:

for i in range(1,len(zen),2):
    print(zen[i])

它从 1 开始,步进为 2,所以我只会做赔率

正如评论中的用户指出的那样,有时并非所有键都存在:

for i in zen:
    if (i%2 == 0):
         print(zen[i])

另一种更短的方法是列表理解,但是它有点不寻常,因为您真的不需要列表。

[print(zen[i]) for i in zen if i%2==1]

关于python - 仅打印奇数字典键及其项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52397633/

相关文章:

python - 如何找出我的 Mac 上安装了哪些 Python 库?

python - Tipfy: 如何在模板中显示 blob?

python - MySQL - 匹配两个包含巨大数据的表并找到相似的数据

python - 使用 Pandas 选择、切片和聚合时态数据

python - lxml:调用etree.iterparse(f)时获取文件当前行号

python - 列出 Python 中函数期望的变量?

python - 将完整的 QUEEN 邻居数组保存到 Pysal 中的 CSV(人口普查 block 组)

python - 如何使用 python 取消缩短 URL?

python - 如何在seaborn fiddle 图上使用箱线图的 mustache 参数?

python - -s 简单英语的意思