How to create a list of tuples from the values of a dictionary of lists?
本问题已经有最佳答案,请猛点这里访问。
字典
1 2 3 4 5 6 7 8 9 10 11 12 | {'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)]...} |
我希望能够将所有键的值保存在一个元组列表中,以便与其他列表进行比较。
到目前为止,我已经尝试过以下代码:
1 2 3 4 5 | from pprint import pprint list_from_dict = [] for keys in my_entities: list_from_dict = [].append(my_entities.values()) pprint(list_from_dict) |
号
输出
我想要的输出如下:
1 2 3 4 5 6 7 | [ (1508, 1512), (2882, 2886), (3011, 3015), (3192, 3196), (3564, 3568), (6453, 6457), (55, 67), (1499, 1503), (1823, 1827), (7455, 7459),...] |
我该如何调整代码来做到这一点?
事先谢谢!
编辑:
我没有找到另一个答案,因为它没有关键字
使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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)] |
或:
1 | print(list(chain.from_iterable(d.values()))) |
号