From the course: Python Essential Training
Unlock the full course today
Join today to access over 24,700 courses taught by industry experts.
Dictionary comprehensions - Python Tutorial
From the course: Python Essential Training
Dictionary comprehensions
Dictionary comprehensions are used to generate dictionaries from iterable structures. Just like list comprehensions create a new list, a dictionary comprehension creates a new dictionary. I'll show you a basic example. So here we have a list of tuples that we'll be using as our key value pairs. Remember, tuples work just like lists, except that you can't alter the value of tuples once they've been declared. And we can create a dictionary from this list of tuples like this. equals item zero colon item one for item in animal list. And there we see our dictionary. There's this familiar for item in list statement, exactly the same in both list and dictionary comprehensions. But now we need to define both the key and the value separated by a colon instead of just a single value like we did for the list comprehension. And of course, this dictionary comprehension is surrounded with the curly braces, just like the list comprehension was surrounded by the square brackets. Now there's a more…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.