迭代字典以使用单循环获取所有元素

时间:2016-01-22 17:03:04

标签: python dictionary

考虑像这样的字典

a_dict = {"a":1,"b":3,"c":4}
b_dict = {"d":44,"e":23}
for (k,v),(k1,v1) in zip(a_dict.items(),b_dict.items()):
    print(k,v);
    print(k1,v1);

使用这段代码我从每个字典中得到两个元素。喜欢:

b 3  
e 23  
c 4  
d 44

我没有得到:

a 1

来自字典a_dict 但我希望每个字典中的所有元素都使用一个循环,该循环是来自a_dict的三个元素和来自b_dict的两个元素。有没有简单的方法来完成这项任务?

3 个答案:

答案 0 :(得分:2)

问题是zip()在到达较小序列的末尾时停止。如果您想要不同的东西,可以使用itertools.zip_longest()

from itertools import zip_longest
a_dict = {"a":1,"b":3,"c":4}
b_dict = {"d":44,"e":23}
for a_pair,b_pair in zip_longest(a_dict.items(),b_dict.items()):
    if a_pair:
        print(a_pair[0],a_pair[1])
    if b_pair:
        print(b_pair[0],b_pair[1]);

答案 1 :(得分:0)

链接这两个项目会为您提供循环中的所有键值对:

from itertools import chain

a_dict = {"a":1,"b":3,"c":4}
b_dict = {"d":44,"e":23}

for k, v in chain(a_dict.items(),b_dict.items()):
    print(k, v)

输出:

c 4
a 1
b 3
e 23
d 44

答案 2 :(得分:-2)

低技术方法是遍历你的词典,依次处理每个词典:

a_dict = {"a":1,"b":3,"c":4}
b_dict = {"d":44,"e":23}
for c in (a_dict, b_dict):
    for (k,v) in (c.iteritems()):
        print(k,v);

输出:

('a', 1)
('c', 4)
('b', 3)
('e', 23)
('d', 44)