# Loop through dictionary in value order
di = {'a': 3, 'b': 1, 'c': 2}
tmp = sorted( [(v, k) for k, v in di.items()] )
print(tmp)
# [(1, 'b'), (2, 'c'), (3, 'a')]
loop throughthe key and the values of a dict in python
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)
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("
Iterating 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
# iterating through dictionary keys fast
dictKeys = list(nameOfDict.keys())
for i in range(len(dictKeys)):
print(dictKeys[i])
# iterating through dictionary values fast
dictValues = list(nameOfDict.values())
for i in range(len(dictKeys)):
print(dictKeys[i])
jjj = {'chuck': 1, 'fred': 42, 'jan': 100}
# If you want only the keys
for key in jjj:
print(key)
# if you want only the values
for key in jjj:
print(jjj[key])
# if you want both keys and values with items
# Using the above you can get either key or value separately if you want
for key, value in jjj.items():
print(key, value)
{%- for drink_attribute, ingredient in drink.items()
if drink_attribute.startswith('strIngredient') and ingredient
%}
<td>{{ ingredient }}</td>
{%- endfor %}