xxxxxxxxxx
Python dictionary[ a type of mapping data type] iterates only keys()
xxxxxxxxxx
a_dict = {'apple':'red', 'grass':'green', 'sky':'blue'}
for key in a_dict:
print key # for the keys
print a_dict[key] # for the values
xxxxxxxxxx
a_dict = {"color": "blue", "fruit": "apple", "pet": "dog"}
# Will loop through the dict's elements (key, value) WITHOUT ORDER
for key, value in a_dict.items():
print(key, '->', value)
xxxxxxxxxx
students = {
'John': 85,
'Emily': 92,
'Michael': 78,
'Sarah': 89
}
for student in students:
print(student, students[student])
xxxxxxxxxx
Titanic_cast = {
"Leonardo DiCaprio": "Jack Dawson",
"Kate Winslet": "Rose Dewitt Bukater",
"Billy Zane": "Cal Hockley",
}
print("Iterating through keys:")
for key in Titanic_cast:
print(key)
print("\nIterating through keys and values:")
for key, value in Titanic_cast.items():
print("Actor/ Actress: {} Role: {}".format(key, value))
# output -
# Iterating through keys:
# Billy Zane
# Leonardo DiCaprio
# Kate Winslet
# Iterating through keys and values:
# Actor/ Actress: Billy Zane Role: Cal Hockley
# Actor/ Actress: Leonardo DiCaprio Role: Jack Dawson
# Actor/ Actress: Kate Winslet Role: Rose Dewitt Bukater
xxxxxxxxxx
dictionary_name={"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for key in dictionary_name.keys():
print(key)
xxxxxxxxxx
foreach (var (key, value) in someDictionary) // loop through key and value; WARNING: NON-MUTABLE
xxxxxxxxxx
<dl>
{% for key, value in my_dict.items() %}
<dt>{{ key|e }}</dt>
<dd>{{ value|e }}</dd>
{% endfor %}
</dl>
xxxxxxxxxx
{%- for drink_attribute, ingredient in drink.items()
if drink_attribute.startswith('strIngredient') and ingredient
%}
<td>{{ ingredient }}</td>
{%- endfor %}