Given
userplays = { "Alice" : { "AC/DC" : 2,
"The Raconteurs" : 3,
"Mogwai" : 1
},
"Bob" : { "The XX" : 4,
"Lady Gaga" : 3,
"Mogwai" : 1,
"The Raconteurs" : 1
},
"Charlie" : { "AC/DC" : 7,
"Lady Gaga" : 7
}
}
get a list of all bands:
['Lady Gaga', 'Mogwai', 'AC/DC', 'The Raconteurs', 'The XX']
I can do
list(set(flatten([ [ band
for band
in playcounts.keys() ]
for playcounts
in userplays.values() ] ) ) )
where flatten is from Flatten (an irregular) list of lists, but is it possible without flatten, using only list/dict comprehensions?
Another way is to use a dict comprehension (Python 2.7+):
Produces:
At least in Python 3.3, this is also faster:
Output:
Edit
Just for pure curiosity, I compared the various way that this can be done in a one-liner.
Here are the results:
You can see that the set comprehension is fastest, followed by a dict comprehension.
Here is the code that generated that Perl style benchmark: