Professional Documents
Culture Documents
Dict1 (:::::) (Dict1) : "University" "KLU" "Name" "Smith" "Branch" "CSIT" "Cgpa" "Pass"
Dict1 (:::::) (Dict1) : "University" "KLU" "Name" "Smith" "Branch" "CSIT" "Cgpa" "Pass"
Dict1 (:::::) (Dict1) : "University" "KLU" "Name" "Smith" "Branch" "CSIT" "Cgpa" "Pass"
Dictionaries are written with curly brackets, and have keys and values:
Example
Create and print a dictionary:
dict1 = {
"university": "KLU",
"name": "Smith",
"branch": "CSIT",
"cgpa": 9.82,
"pass": True
}
print(dict1)
Dictionary Items
Dictionary items are ordered, changeable, and does not allow duplicates.
Example
Print the "name" value of the dictionary:
dict1 = {
"university": "KLU",
"name": "Smith",
"branch": "CSIT",
"cgpa": 9.82,
"pass": True
}
print(dict1["name"])
Dictionary Length
To determine how many items a dictionary has, use the len() function:
Example
Print the number of items in the dictionary:
dict1 = {
"university": "KLU",
"name": "Smith",
"branch": "CSIT",
"cgpa": 9.82,
"pass": True
}
print(len(dict1))
dict1 = {
"university": "KLU",
"name": "Smith",
"branch": "CSIT",
"cgpa": 9.82,
"pass": True
}
print(dict1.keys())
dict1 = {
"university": "KLU",
"name": "Smith",
"branch": "CSIT",
"cgpa": 9.82,
"pass": True
}
print(dict1.items())
When looping through a dictionary, the return value are the keys of the
dictionary, but there are methods to return the values as well.
Example
Print all key names in the dictionary, one by one:
dict1 = {
"university": "KLU",
"name": "Smith",
"branch": "CSIT",
"cgpa": 9.82,
"pass": True
}
for i in dict1 :
print(i)
Example
Print all values in the dictionary, one by one:
dict1 = {
"university": "KLU",
"name": "Smith",
"branch": "CSIT",
"cgpa": 9.82,
"pass": True
}
for i in dict1 :
print(dict1[i])
To print type of values in a dictionary
dict1 = {
"university": "KLU",
"name": "Smith",
"branch": "CSIT",
"cgpa": 9.82,
"pass": True
}
for i in dict1 :
print(type(dict1[i]))
Example
You can also use the values() function to return values of a dictionary:
dict1 = {
"university": "KLU",
"name": "Smith",
"branch": "CSIT",
"cgpa": 9.82,
"pass": True
}
for i in dict1.values() :
print(i)