开发者

List comprehension to extract a list of tuples from dictionary

开发者 https://www.devze.com 2023-02-17 20:38 出处:网络
I\'d like to use list comprehension on the following list; movie_dicts = [{\'title\':\'A Boy and His Dog\', \'year\':1975, \'rating\':6.6},

I'd like to use list comprehension on the following list;

movie_dicts = [{'title':'A Boy and His Dog', 'year':1975, 'rating':6.6},
           {'title':'Ran', 'year':1985, 'rating': 8.3},
           {'title':'True Grit', 'year':2010, 'rating':8.0},
           {'title':'Scanners', 'year':1981, 'rating': 6.7}]

using my knowledge of list comprehension and dictionaries, I know that

movie_titles = [x['title'] for x in movie_dicts]
print movie_titles

will print a list with movie titles.

In order to extracts a list of (title, year) tuples I've tried -

movie_tuples = [x for ('title','year') in movie_dicts]
print movie_tuples

and I receive the error SyntaxError: can't assign to literal

I'm unsure on how to fetch the two (specific) 开发者_StackOverflow中文版key/value pairs using list comprehension (doing so would generate a tuple automatically?)


movie_dicts = [
    {'title':'A Boy and His Dog', 'year':1975, 'rating':6.6},
    {'title':'Ran', 'year':1985, 'rating': 8.3},
    {'title':'True Grit', 'year':2010, 'rating':8.0},
    {'title':'Scanners', 'year':1981, 'rating': 6.7}
]

title_year = [(i['title'],i['year']) for i in movie_dicts]

gives

[('A Boy and His Dog', 1975),
 ('Ran', 1985),
 ('True Grit', 2010),
 ('Scanners', 1981)]

OR

import operator
fields = operator.itemgetter('title','year')
title_year = [fields(i) for i in movie_dicts]

which gives exactly the same result.


This version has a minimum of repeating yourself:

>>> fields = "title year".split()
>>> movie_tuples = [tuple(map(d.get,fields)) for d in movie_dicts]


[(movie_dict['title'], movie_dict['year']) for movie_dict in movie_dicts]

Remember, xs = [expr for target in expr2] is equivalent (almost - ignoring StopIteration for simplicity) to:

xs = []
for target in expr2:
    xs.append(expr)

So target needs to be a plain old variable name or some tuple to unpack to. But since movie_dicts doesn't contain sequences to unpack from but simple single values (dicts), you must limit it to one variable. Then when you append to the list being generated, you can create a tuple and do whatever else you want to do with the current item.


If you don't have to use a list comprehension, you could always do:

list(d.iteritems())
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号