reading dictionary in python code example
Example 1: dictionary in python
#A dictionary has key-value pairs. Here 1,2,3 are the keys and Item1,Item2,Item3
#are their values respectively.
dictionaryName = { 1: "Item1", 2: "Item2", 3: "Item3"}
#retrieving value of a particular key
dictionaryName[1]
#retrieving all the keys in a dictionary
dictionaryName.keys()
#retrieving all the values in a dictionary
dictionaryName.values()
Example 2: how to print a value from a dictionary in python
dictionary={
"Jeff":{
"lastname":"bobson",
"age":55,
"working":True
},
"James":{
"lastname":"Bobson",
"age":34,
"working":False
}
}
# For a good format:
for i in dictionary:
print(i, ":")
for j in dictionary[i]:
print(" ", j, ":", dictionary[i][j])
print()
# Output:
Jeff :
lastname : bobson
age : 55
working : True
James :
lastname : Bobson
age : 34
working : False
# For just a quick reading:
for k, v in dictionary.items():
print(k, v)
# Output:
Jeff {'lastname': 'bobson', 'age': 55, 'working': True}
James {'lastname': 'Bobson', 'age': 34, 'working': False}