How to create a list of tuples from the values of a dictionary of lists? [duplicate]
Clash Royale CLAN TAG#URR8PPP
How to create a list of tuples from the values of a dictionary of lists? [duplicate]
This question already has an answer here:
The dictionary my_entities
looks like this:
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)]...
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
.
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!
dictionary
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
my_entities.values()
itertools.chain.from_iterable(my_entities.values())
1 Answer
1
Use chain
or chain.from_iterable
from itertools
module:
chain
chain.from_iterable
itertools
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())))
It's a simple flattening operation over
my_entities.values()
. So [t for v in my_entities.values() for t in v]` oritertools.chain.from_iterable(my_entities.values())
if you need an iterator only.– Martijn Pieters♦
Aug 12 at 14:03