简体   繁体   中英

Python CSV writerows and List comprehension

I have the following structure, I need to save it with csv.writerows() hence I want to have a list of lists.

Each element is a dictionary (key + list) which I need to unpack and then convert it to a list of lists.

  results = [{'06079467037ACD8AMV': ['US', 'IT', 3065, 'NOT_FOUND']}, {'A557288EDE635FD6MV': ['US', 'Cars 3', 2604, 'NOT_FOUND']}, {'0367F463382D27FBMV': ['US', 'Kingsman: The Golden Circle', 1580, 'NOT_FOUND']}]

Example:

[['06079467037ACD8AMV', 'US', 'IT', 3065, 'NOT_FOUND'], ['A557288EDE635FD6MV', 'US', 'Cars 3', 2604, 'NOT_FOUND'], ['0367F463382D27FBMV', 'US', 'Kingsman: The Golden Circle', 1580, 'NOT_FOUND']]

Any idea? I tried the following code with no luck:

 [[k]+v for k,v in movie.iteritems() for movie in results]

您只需将列表理解子句向后:

[[k]+v for movie in results for k,v in movie.iteritems()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM