首页 > 解决方案 > Python:迭代字典中的一些键:值对,但不是整个字典

问题描述

我有一系列字典,基本上都有相同的键,但每个字典分配的值不同。

为简单起见,假设我有 3 个字典:

dict_one = {
    "three letter code": "Arg:",
    "C": 1,
    "H": 2,
    "N": 3,
    "O": 4,
    "a_string": "nope",
}


dict_two = {
    "three letter code": "Doh:",
    "C": 5,
    "H": 6,
    "N": 7,
    "O": 8,
    "a_string": "nah",
}

dict_three = {
    "three letter code": "Uhg:",
    "C": 9,
    "H": 10,
    "N": 11,
    "O": 12,
    "a_string": "no",
}

假设我想遍历这些字典中的每一个并将键中包含的值乘以"C" and "N" and "O"4。因为它们是整数。我们用整数做数学。

我不想乘"three letter code" or "a_string"因为它们是字符串,乘以字符串有什么意义,对吗?(有,只是不适合我的情况)。

如果您有解决此问题的好方法,那么请务必成为我的客人。

但我在想,因为我所有的字典都有连续顺序的键:值对,我想知道是否可以像循环列表中的索引块/范围一样循环它们。例如:

arr = ["zero", "one", "two", "three", "four", "five"]

for i in range(2, 5):
    print(arr[i])

不会循环并打印完整列表,而是仅产生以下输出:

two
three
four

字典是否可以使用类似的循环方法?如果不是,那也没关系,我很感激花时间帮助一个对编码知之甚少的生物学生。

标签: pythondictionary

解决方案


(您的问题是XY 问题的典型说明:-))

您可以使用该type()函数仅乘以整数值:

import pprint                        # Only for nice test print

dict_one = {
    "three letter code": "Arg:",
    "C": 1,
    "H": 2,
    "N": 3,
    "O": 4,
    "a_string": "nope",
}

for key in dict_one:
    if type(dict_one[key]) is int:
        dict_one[key] *= 4

pprint.pprint(dict_one)

输出:

{'C': 4,
 'H': 8,
 'N': 12,
 'O': 16,
 'a_string': 'nope',
 'three letter code': 'Arg:'}

推荐阅读