python中是否有一种方法可以在循环的一次迭代中在字典中循环多个键值对

时间:2018-08-16 23:18:25

标签: python python-3.x dictionary python-3.6

我有以下示例代码,是否想知道Python中是否有一种方法可以在单个循环迭代中循环多个键值对?如果您看到我的示例,我有一个包含四个键值对的字典,那么python中是否有一种方法可以单次循环呢?

ID   Model_12 Model_24 Model_88
111      0       2       8
222      9       10      17
234      0       0       6

my_dict = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}

count = 1
for key, value in my_dict.items():
    print('the count is {} the key is {} and the value is {}'.format(count, key, value))

    count += 1

期望的返回数据如下所示

the count is 1 the key is key4 and the value is value4
the count is 2 the key is key3 and the value is value3
the count is 3 the key is key1 and the value is value1
the count is 4 the key is key2 and the value is value2

1 个答案:

答案 0 :(得分:2)

您可以将list comprehensionenumerate一起使用以保持当前索引。

import os

out = 'count: {}, key: {}, val: {}'
my_dict = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'}
os.linesep.join([out.format(c, *kv) for c, kv in enumerate(my_dict.items())])

输出:

count: 0, key: key3, val: value3
count: 1, key: key2, val: value2
count: 2, key: key1, val: value1
count: 3, key: key4, val: value4

条件示例:

要在评论中回答问题,如果您要根据条件添加或不添加项目(顺便说一句,可以添加更多if

[(c, *kv) for c, kv in enumerate(my_dict.items()) if c % 0 and len(kv[1]) < 5)

还考虑...

def do_something(c, kv):
    key, value = kv
    if key == 'key1':
        pass  # do something

    # somewhere return True or False depending on your logic

[(c, *kv) for c, kv in enumerate(my_dict.items()) if do_something(c, kv)