如何从列表字典的值创建元组列表?

时间:2018-08-12 13:59:29

标签: python list dictionary tuples

字典my_entities如下所示:

{'Alec': [(1508, 1512),
          (2882, 2886),
          (3011, 3015),
          (3192, 3196),
          (3564, 3568),
          (6453, 6457)],
 'Downworlders': [(55, 67)],
 'Izzy': [(1499, 1503), (1823, 1827), (7455, 7459)],
 'Jace': [(1493, 1497),
          (1566, 1570),
          (3937, 3941),
          (5246, 5250)]...}

我希望能够将所有键的值保存在一个元组列表中,以便与其他列表进行一些比较。

到目前为止,我已经尝试了以下代码:

from pprint import pprint    
list_from_dict = []
for keys in my_entities:
    list_from_dict = [].append(my_entities.values())
pprint(list_from_dict)

并输出None

我想要的输出看起来像这样:

[         (1508, 1512),
          (2882, 2886),
          (3011, 3015),
          (3192, 3196),
          (3564, 3568),
          (6453, 6457),
          (55, 67), (1499, 1503), (1823, 1827), (7455, 7459),...]

我如何调整代码来做到这一点?

谢谢!

编辑

由于找不到关键字dictionary,因此没有找到其他答案。如果确实将其视为重复项,则可以将其删除-我有我的答案。谢谢!

1 个答案:

答案 0 :(得分:0)

使用itertools模块中的chainchain.from_iterable

from itertools import chain

d = {'Alec': [(1508, 1512),
          (2882, 2886),
          (3011, 3015),
          (3192, 3196),
          (3564, 3568),
          (6453, 6457)],
 'Downworlders': [(55, 67)],
 'Izzy': [(1499, 1503), (1823, 1827), (7455, 7459)],
 'Jace': [(1493, 1497),
          (1566, 1570),
          (3937, 3941),
          (5246, 5250)]}

print(list(chain(*d.values())))

# [(1508, 1512), (2882, 2886), (3011, 3015), (3192, 3196), (3564, 3568),
#  (6453, 6457), (55, 67), (1499, 1503), (1823, 1827), (7455, 7459),
#  (1493, 1497), (1566, 1570), (3937, 3941), (5246, 5250)]

或者:

print(list(chain.from_iterable(d.values())))