xxxxxxxxxx
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)
xxxxxxxxxx
dictionary = {52:"E",126:"A",134:"B",188:"C",189:"D"}
for key, value in dictionary.items():
print(key)
print(value)
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
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print key, 'corresponds to', d[key]
xxxxxxxxxx
my_dic = {
'name': 'Majhi',
'age': 71,
'country': 'BD'
}
for key, value in my_dic.items():
print(key) # name age country
print(value) # Majhi 71 BD
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
foreach (var (key, value) in someDictionary) // loop through key and value; WARNING: NON-MUTABLE