Last active
August 29, 2015 14:13
-
-
Save tudormunteanu/1eda7e9f7c5c9dc989e4 to your computer and use it in GitHub Desktop.
Python Iterations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Plain Lists | |
list = ["a", "b", "c"] | |
for v in list: | |
print v | |
#Outputs: | |
#a | |
#b | |
#c | |
#Dictionaries, only by keys | |
dict = {"a": 1, "b": 2, "c": 3} | |
for v in dict: | |
print v | |
#Outputs: | |
#a | |
#b | |
#c | |
#Dictionaries, with keys, printing the associated value | |
dict = {"a": 1, "b": 2, "c": 3} | |
for v in dict: | |
print v | |
print dict[v] | |
#Outputs: | |
#a | |
#1 | |
#c | |
#3 | |
#b | |
#2 | |
#This is equivalent to for k in dict.keys():..., but much faster. | |
#Dictionaries, with unpacked keys and values | |
dict = {"a": 1, "b": 2, "c": 3} | |
for k, v in dict.items(): #or .iteritems() in Python <3.x | |
print k | |
print v | |
#Outputs: | |
#a | |
#1 | |
#c | |
#3 | |
#b | |
#2 | |
#Dictionaries, by accessing only the values | |
dict = {"a": 1, "b": 2, "c": 3} | |
for v in dict.itervalues(): | |
print v | |
#Outputs: | |
#1 | |
#2 | |
#3 | |
#Getting a list of keys from a dictionary | |
dict = {"a": 1, "b": 2, "c": 3} | |
print dict.keys() | |
#Outputs: | |
#['a', 'c', 'b'] | |
#Getting a list of values from a dictionary | |
dict = {"a": 1, "b": 2, "c": 3} | |
print dict.values() | |
#Outputs: | |
#[1, 3, 2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment