同时枚举2个python字典的值?

时间:2019-06-21 10:20:26

标签: python dictionary zip google-colaboratory

我必须词典:

dic_of_dics1 = {1: {"a": "A"}, 2: {"a": "B"}, 3: {"a": "C"}}
dic_of_dics2 = {1: {"d": "20"}, 2: {"d": "30"}, 3: {"d": "40"}}

我想同时枚举字典的值;与此类似:Enumerate two python lists simultaneously?

for index, (value1, value2) in enumerate(zip(dic_of_dics1, dic_of_dics2)):
print (value1, value2, subkey1, subkey2, index) 

所需的输出:

A, 20, a, d, 0
B, 30, a, d, 1
C, 40, a, d, 2

4 个答案:

答案 0 :(得分:2)

为您简化的情况:

dic_of_dics1 = {1: {"a": "A"}, 2: {"a": "B"}, 3: {"a": "C"}}
dic_of_dics2 = {1: {"d": "20"}, 2: {"d": "30"}, 3: {"d": "40"}}

for val1, val2 in zip(dic_of_dics1.values(), dic_of_dics2.values()):
    print('{}, {}'.format(list(val1.values())[0], list(val2.values())[0]))

输出:

A, 20
B, 30
C, 40

更新(甚至更短):

for i, (d1, d2) in enumerate(zip(dic_of_dics1.values(), dic_of_dics2.values())):
    (k1, v1), (k2, v2) = *d1.items(), *d2.items()
    print(v1, v2, k1, k2, i, sep=', ')

输出:

A, 20, a, d, 0
B, 30, a, d, 1
C, 40, a, d, 2

答案 1 :(得分:1)

通过解压缩和排序并添加索引来获得另一个更具可读性和更强大的版本:

dic_of_dics1 = {2: {"a": "B"}, 1: {"a": "A"}, 3: {"a": "C"}}
dic_of_dics2 = {1: {"d": "20"}, 2: {"d": "30"}, 3: {"d": "40"}}

for i, k in enumerate(sorted(dic_of_dics1)):
    dic1, dic2 = dic_of_dics1[k], dic_of_dics2[k]
    (k_a,), (a,), (k_b,), (b,) = dic1.keys(), dic1.values(), dic2.keys(), dic2.values()
    print(', '.join([a, b, k_a, k_b, str(i)]))

输出:

A, 20, a, d, 0
B, 30, a, d, 1
C, 40, a, d, 2

我认为,取决于字典键的顺序是个坏主意。

答案 2 :(得分:0)

尝试一下。

dic_of_dics1 = {1: {"a": "A"}, 2: {"a": "B"}, 3: {"a": "C"}}
dic_of_dics2 = {1: {"d": "20"}, 2: {"d": "30"}, 3: {"d": "40"}}

new_dict = {}
for i in dic_of_dics1:
    new_dict[list(dic_of_dics1[i].values())[0]] = list(dic_of_dics2[i].values())[0]
print(new_dict)

OR

enumerate with zip-使用枚举和zip遍历两个列表及其索引

new_dict={}

for index,(value1, value2) in enumerate(zip(dic_of_dics1.values(), dic_of_dics2.values())):
    new_dict[list(value1.values())[0]] = list(value2.values())[0]

print(new_dict)

O / P:

{'A': '20', 'B': '30', 'C': '40'}

答案 3 :(得分:0)

可选的单线:

print('\n'.join([', '.join([list(x.values())[0], list(y.values())[0]]) for x, y in zip(dic_of_dics1.values(), dic_of_dics2.values())]))

输出:

A, 20
B, 30
C, 40