AlphaCodingSkills

Python - Dictionary of Dictionaries


Advertisements

A dictionary can be created inside a dictionary, which is also called nested dictionary or dictionary of dictionaries. The below mentioned program describes two ways for creating nested dictionary.

Info = {
   "person1": {
      "name": "John",
      "age": 25,
      "city": "London"
    },
   "person2": {
      "name": "Marry",
      "age": 20,
      "city": "Newyork"
    },
   "person3": {
      "name": "Sam",
      "age": 30,
      "city": "Paris"
    }
}
print(Info["person2"])

Output

{'name': 'Marry', 'age': 20, 'city': 'Newyork'}

The inner dictionaries can be created outside and combined later with the outer dictionary.

person1 = {
  "name": "John",
  "age": 25,
  "city": "London"
}
person2 = {
  "name": "Marry",
  "age": 20,
  "city": "Newyork"
}
person3 = {
  "name": "Sam",
  "age": 30,
  "city": "Paris"
}
Info = {
	"person1": person1,
	"person2": person2,
	"person3": person3
}
print(Info["person2"])

Output

{'name': 'Marry', 'age': 20, 'city': 'Newyork'}

Dictionary Methods & Functions
MethodsDescription
clear() Deletes all elements of the dictionary
copy() Returns a copy of the dictionary
fromkeys() Creates a dictionary with specified keys and values
get() Returns value of the specified key
items() Returns a list of tuples with each key-value pair in tuple
keys() Returns a list of all keys of the dictionary
pop() Removes specified key-value pair of the dictionary
popitem() Removes the last key-value pair of the dictionary
setdefault() Checks specified key in the dictionary. If the key does not exist, it inserts the specified key with specified value
update() Updates the dictionary with the specified key-value pair(s)
values() Returns a list of all values of the dictionary
FunctionsDescription
len() Returns total number of elements in the dictionary
dict() Creates dictionary using an iterable object containing key-value pairs