AlphaCodingSkills

Python - Dictionary


Advertisements

Previous Page Next Page

A Dictionary is a type of data container in Python which is used to store multiple data in one variable. It can contain elements of different data types. Elements in a dictionary are unordered and hence it is not possible to access dictionary's element using index number. Dictionary's elements are immutable and hence not changeable. Additionally, it does not allow multiple elements with same values (no duplicate elements.)

Create Dictionary

Dictionary contains data in key-value pair. It can be created by separating it's elements by comma (,) and enclosing with curly bracket { }. Additionally, it can also be created using dict() function.

#Dictionary with multiple datatypes
Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
print(Info)

#Creating dictionary with constructor
Info = dict(name="Marry", age=20, city="Newyork")
print(Info)

Output

{'name': 'John', 'age': 25, 'city': 'London'}
{'name': 'Marry', 'age': 20, 'city': 'Newyork'}

Access element of a Dictionary

An element of a dictionary can be accessed using key enclosed by square brackets [ ]. The same can also be achieved using get() method.

Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
print(Info["city"])
print(Info.get("name"))

Output

London
John

Modify values in Dictionary

To modify value, assign new value using key.

Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
Info["city"] = "Paris"
print(Info)

Output

{'name': 'John', 'age': 25, 'city': 'Paris'}

Dictionary Length

The len() function can be used to find out total number of key-value pairs in the dictionary.

Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
print(len(Info))

Output

3

Loop over Dictionary's keys

This method can be used to access dictionary's keys one by one.

Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
for x in Info:
  print(x)

Output

name
age
city

Loop over Dictionary's values

This method can be used to access dictionary's values one by one.

Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
#first method
for x in Info:
  print(Info[x])
#second method
for x in Info.values():
  print(x)

Each method gives the same result.

Output

John
25
London

Check a Key in the Dictionary

The in keyword can be used to check whether a specified key is present in the dictionary or not.

Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
if "lastname" in Info:
  print("Yes, 'lastname' is a key in the dictionary.")
else:
  print("No, 'lastname' is not a key in the dictionary.")

Output

No, 'lastname' is not a key in the dictionary.

Add elements in Dictionary

This can be achieved by assigning values to new index key.

Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
Info["gender"] = "Male"
print(Info)

Output

{'name': 'John', 'age': 25, 'city': 'London', 'gender': 'Male'}

Delete elements of a Dictionary

There are number of ways to delete elements from a dictionary:

  • pop() - deletes specified key and it's value of the dictionary.
  • popitem() - deletes last key-value pair of the dictionary. Please note that dictionary is an unordered data container, hence last key-value pair is not defined.
  • clear() - deletes all key-value pairs of the dictionary.
  • del - deletes a key-value pair of a dictionary. can be used to delete the dictionary itself.

Example 1:


Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
Info.pop("city")
print(Info)

Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
Info.popitem()
print(Info)

Output

{'name': 'John', 'age': 25}
{'age': 25, 'city': 'London'}

Example 2:


Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
Info.clear()
print(Info)

Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
del Info["city"]
del Info

Output

{}
{'name': 'John', 'age': 25}
NameError: name 'Info' is not defined

Copy Dictionary

The copy of a dictionary can be created using either + operator or copy() method.

  • = operator: Using dict2 = dict1, a reference of dict1 can be created into dict2. Any change to dict1 will be reflected in dict2 also.
  • copy(): This will create an independent copy of a dictionary.

Info = {
   "name": "John",
   "age": 25,
   "city": "London"
}
Info_1 = Info
Info_2 = Info.copy()

print(Info_1)     #'Info_1' dictionary is a reference of 'Info'
print(Info_2)     #'Info_2' dictionary is a copy of 'Info'

Info.pop("city")  #deletes 'city' key from the dictionary

print(Info_1)     #'city' key deleted from 'Info' and 'Info_1'
print(Info_2)     #no change


Output

{'name': 'John', 'age': 25, 'city': 'London'}
{'name': 'John', 'age': 25, 'city': 'London'}

{'name': 'John', 'age': 25}
{'name': 'John', 'age': 25, 'city': 'London'}





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

Previous Page Next Page