Learn Python: Iterators for Dictionaries

Iterators for Dictionaries




Let’s start with iterating over a dictionary. Recall that a dictionary is just a collection of keys and values.
d = { "Name": "Guido", "Age": 56, "BDFL": True } print d.items() # => [('BDFL', True), ('Age', 56), ('Name', 'Guido')]
Note that the .items() method doesn’t return key/value pairs in any specific order.

keys() and values()




While .items() returns an array of tuples with each tuple consisting of a key/value pair from the dictionary:
  • The .keys() method returns a list of the dictionary’s keys, and
  • The .values() method returns a list of the dictionary’s values.



Again, these methods will not return the keys or values from the dictionary in any specific order.
You can think of a tuple as an immutable (that is, unchangeable) list. Tuples are surrounded by ()s and can contain any data type.

The 'in' Operator

For iterating over lists, tuples, dictionaries, and strings, Python also includes a special keyword: in. You can use in very in tuitively, like so:
for number in range(5): print number, d = { "name": "Emma", "age": 17 } for key in d: print key, d[key], for letter in "Emma": print letter, # note the comma!



  1. In the example above, first, we create and iterate through a range, printing out 0 1 2 3 4. Note that the trailing comma ensures that we keep printing on the same line.
  2. Next, we create a dictionary and iterate through, printing out age 17 name Emma. Dictionaries have no specific order.
  3. Finally, we iterate through the letters of a string, printing out E m m a.

Building Lists

Let’s say you wanted to build a list of the numbers from 0 to 50 (inclusive). We could do this pretty easily:
my_list = range(51)
But what if we wanted to generate a list according to some logic—for example, a list of all the even numbers from 0 to 50?
Python’s answer to this is list comprehension. List comprehensions are a powerful way to generate lists using the for/in and if keywords we’ve learned.

List Comprehension Syntax




Here’s a simple example of list comprehension syntax:

new_list = [x for x in range(1, 6)] # => [1, 2, 3, 4, 5]
This will create a new_list populated by the numbers one to five. If you want those numbers doubled, you could use:
doubles = [x * 2 for x in range(1, 6)] # => [2, 4, 6, 8, 10]
And if you only wanted the doubled numbers that are evenly divisible by three:
doubles_by_3 = [x * 2 for x in range(1, 6) if (x * 2) % 3 == 0] # => [6]

List Slicing Syntax

Sometimes we only want part of a Python list. Maybe we only want the first few elements; maybe we only want the last few. Maybe we want every other element!
List slicing allows us to access elements of a list in a concise manner. The syntax looks like this:
[start:end:stride]
Where start describes where the slice starts (inclusive), end is where it ends (exclusive), and stride describes the space between items in the sliced list. For example, a stride of 2 would select every other item from the original list to place in the sliced list.

Omitting Indices

If you don’t pass a particular index to the list slice, Python will pick a default.
to_five = ['A', 'B', 'C', 'D', 'E'] print to_five[3:] # prints ['D', 'E'] print to_five[:2] # prints ['A', 'B']
print to_five[::2] # print ['A', 'C', 'E']
  1. The default starting index is 0.
  2. The default ending index is the end of the list.
  3. The default stride is 1.

Reversing a List

We have seen that a positive stride progresses through the list from left to right.
negative stride progresses through the list from right to left.
letters = ['E', 'L', 'I', 'M', 'S'] print letters[::-1]
''' I Love Your Smile :) '''
In the example above, we print out ['S', 'M', 'I', 'L', 'E'].

Stride Length

A positive stride length traverses the list from left to right, and a negative one traverses the list from right to left.
Further, a stride length of 1 traverses the list “by ones,” a stride length of 2 traverses the list “by twos,” and so on.

Anonymous Functions

One of the more powerful aspects of Python is that it allows for a style of programming called functional programming, which means that you’re allowed to pass functions around just as if they were variables or values. Sometimes we take this for granted, but not all languages allow this!


Check out the code at the right. See the lambda bit? Typing
lambda x: x % 3 == 0
Is the same as
def by_three(x): return x % 3 == 0
Only we don’t need to actually give the function a name; it does its work and returns a value without one. That’s why the function the lambda creates is an anonymous function.
When we pass the lambda to filterfilter uses the lambda to determine what to filter, and the second argument (my_list, which is just the numbers 0 – 15) is the list it does the filtering on.
Great We Are Almost Completed or Learned Python Hope You Enjoying Learning and also stay in touch with us visit site frequently to get more intresting articles.
       Don't forget to Share #SharingIsCaring :)  

No comments:

Powered by Blogger.