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) key/value pairs using list comprehension (doing so would generate a tuple automatically?)
We can perform comprehension to sequences such as lists, sets, dictionaries but not to tuples. For example, if we want to perform list comprehension, we use square brackets [ ]. We use curly braces { }, but we would have to use parentheses for the tuple for dictionary comprehension.
We can add a filter to the iterable to a list comprehension to create a dictionary only for particular data based on condition. Filtering means adding values to dictionary-based on conditions.
Convert a Python Dictionary to a List of Tuples Using the List Function. One of the most straightforward and Pythonic ways to convert a Python dictionary into a list of tuples is to the use the built-in list() function. This function takes an object and generates a list with its items.
the choice between tuple or list is based on what you are planning on doing with it and not resources. Apart from the overhead of the conversion, the tuple will be smaller and faster, since it lacks the mechanism to make it mutable, allow fast inserts etc. But the conversion of course costs extra time (once).
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With