data_garden data_garden - 1 month ago 8
Python Question

Python - create tuples from list

given this

dictionary
:

sql_playlists={
'user1':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 1': 1.0},
'user2':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 2': 1.0},
'user3':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 3': 1.0},
'user4':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 4': 1.0},
'user5':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 4': 1.0}}


I can create data tuples of
keys
and
values
like this:

sqltuples = [(k1,k2,v2) for k1,v1 in sql_playlists.items()
for k2,v2 in v1.items()]


which outputs:

[(u'user1', u'Make You Feel My Love', 1.0), (u'user1', u'I See Fire', 1.0), (u'user', u'High And Dry', 1.0), (u'user1', u'Fake Plastic Trees', 1.0), (u'user1', u'One', 1.0), (u'user1', u'Goodbye My Lover', 1.0), (u'user1', u'No Surprises', 1.0)]


for each user.

but what if
sql_playlist
is a
list
, the same data structure but inside
[]
, and not a
dictionary
?

EDIT: the list

sql_playlists=[{
'user1':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 1': 1.0},
'user2':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 2': 1.0},
'user3':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 3': 1.0},
'user4':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 4': 1.0},
'user5':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 4': 1.0}}]


how do I adapt the
list comprehension
in order to produce the same
tuples
from the list?

this works for the first user:

sqltuples = [(k1,k2,v2) for k1,v1 in sql_playlists[0].items()
for k2,v2 in v1.items()]


but i want for all users.

Answer

if you mean array of dictionaries: sql_playlists=[ {'user1':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 1': 1.0}}, {'user2':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 2': 1.0}}, {'user3':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 3': 1.0}}, {'user4':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 4': 1.0}}, {'user5':{'Karma Police':1.0,'Roxanne':1.0,'Sonnet':1.0,'We Will Rock You':1.0,'Song 4': 1.0}}]

then:

sqltuples = [(k1,k2,v2) for vlist in sql_playlists for k1,v1 in vlist.items() for k2,v2 in v1.items()]

you should note that this will produce the tuples in different order because the sorting is preserved when enumerating lists but not dicts