python:字典到字典的元组 [英] python: tuple of dictionary to Dictionary

查看:105
本文介绍了python:字典到字典的元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何转换字典元组,如下面的示例所示:

How can I convert tuple of dictionaries like example present below:

({(1, 2): 3},
 {(1, 3): 5},
 {(1, 4): 5},
 {(2, 4): 5},
 {(1, 5): 10},
 {(2, 6): 9},
 {(1, 6): 9},
 {(2, 1): 2},
 {(2, 2): 3},
 {(2, 3): 5},
 {(2, 5): 10},
 {(1, 1): 2})

更简单的形式,例如字典:

to a rather simpler form like dictionary:

{(1, 1): 2,
 (1, 2): 3,
 (1, 3): 5,
 (1, 4): 5,
 (1, 5): 10,
 (1, 6): 9,
 (2, 1): 12,
 (2, 2): 7,
 (2, 3): 7,
 (2, 4): 3,
 (2, 5): 4,
 (2, 6): 2}

推荐答案

只需对元组进行迭代,并使用字典理解来重建字典"flat":

just iterate on the tuples and rebuild the dictionary "flat" using a dictionary comprehension:

a = ({(1, 2): 3},
 {(1, 3): 5},
 {(1, 4): 5},
 {(2, 4): 5},
 {(1, 5): 10},
 {(2, 6): 9},
 {(1, 6): 9},
 {(2, 1): 2},
 {(2, 2): 3},
 {(2, 3): 5},
 {(2, 5): 10},
 {(1, 1): 2})

b = {k:v for t in a for k,v in t.items()}

print(b)

结果:

{(1, 2): 3, (2, 6): 9, (2, 1): 2, (1, 1): 2, (1, 5): 10, (1, 3): 5, (1, 6): 9, (1, 4): 5, (2, 2): 3, (2, 3): 5, (2, 5): 10, (2, 4): 5}

这篇关于python:字典到字典的元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆