0

The dictionary my_entities looks like this:

{'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)]...}

I would like to be able to save the values of all the keys in a single list of tuples to do some comparisons with other lists.

So far I've tried this code:

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

and it outputs None.

My desired output would look like this:

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

How do I tweak the code to do that?

Thanks in advance!

EDIT:

I didn't find that other answered question due to the fact it doesn't have the keyword dictionary. If it's indeed seen as a duplicate, then it can be deleted - I have my answer. Thanks!

Waldkamel
  • 153
  • 3
  • 13
  • It's a simple flattening operation over `my_entities.values()`. So [t for v in my_entities.values() for t in v]` or `itertools.chain.from_iterable(my_entities.values())` if you need an iterator only. – Martijn Pieters Aug 12 '18 at 14:03

1 Answers1

0

Use chain or chain.from_iterable from itertools module:

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)]

Or:

print(list(chain.from_iterable(d.values())))
Austin
  • 25,759
  • 4
  • 25
  • 48