Dictionary in Python

Dictionary in Python

Dictionary in Python is a containers of key-value pairs. Each key-value pair is an element of the dictionary. Elements in a dictionary are unordered, so they cannot by accessed using the method of indexing. Keys of a dictionary are immutable and duplicate keys are not allowed. Values of key-value pairs can be of any type and different tuples of values for every key-value pair is allowed.

 

 

Create Dictionary in Python

Dictionary can be created by separating its key-value pairs or elements by comma and placing them within curly braces where key and value of a pair is separated by colon or by using dict() function.

 

# Python program to exemplify dictionary creation

#Dictionary with different datatypes
info = {
   "name": "Brandon",
   "age": 21,
   "city": "Paris"
}
print(info)

#Creating dictionary with constructor dict() function
info = dict(name="Brandon", age=21, city="Paris")
print(info)

Output:

{'name': 'Brandon', 'age': 21, 'city': 'Paris'}
{'name': 'Brandon', 'age': 21, 'city': 'Paris'}

 

 

Access Element of a Dictionary in Python

Element of a dictionary can be accessed by indexing it using key name or by using get() method which requires the key name.

 

#Python program to exemplify element access of a dictionary

info = {
   "name": "Bailey",
   "age": 23,
   "city": "London"
}
print(info["city"])
print(info.get("name"))

Output:

London
Bailey

 

 

Modify values in a Dictionary

Value of a key-value pair in a dictionary is modified using the assignment operator =.

 

#Python program to exemplify element modification of a dictionary

info = {
   "name": "Bailey",
   "age": 23,
   "city": "London"
}
print(info.get("city"))
info["city"]="New York"
print(info.get("city"))

Output:

London
New York

 

 

Dictionary Length

Length of a dictionary is the number of key-value pairs it has and it can be acquired by using the function len().

 

#Python program to exemplify len() function of a dictionary

info = {
   "name": "Bailey",
   "age": 23,
   "city": "London"
}
print(len(info))

Output:

3

 

 

Loop over Dictionary’s Keys

Looping over dictionary’s keys can be used to obtain keys of the dictionary one by one.

 

#Python program to exemplify looping over dictionary's keys

info = {
   "name": "Bailey",
   "age": 23,
   "city": "London"
}
for key in info:
  print(key)

Output:

name
age
city

 

 

Loop over Dictionary’s Values

Looping over dictionary’s values can be used to access values of every key-value pair one by one.

 

#Python program to exemplify looping over dictionary's values

info = {
   "name": "Bailey",
   "age": 23,
   "city": "London"
}
#first method to access dictionary's values
for key in info:
  print(info[key])

print()
#second method to access dictionary's values
for value in info.values():
  print(value)

Output:

Bailey
23
London

Bailey
23
London

 

 

Check a Key in a Dictionary

To check if a key exists in a dictionary, if statement along with the in operator is used.

 

#Python program to exemplify if a key is a part of dictionary's keys or not

info = {
   "name": "Victor",
   "age": 23,
   "city": "California"
}
if "firstname" in info:
  print("Yes, 'firstname' is a key in the dictionary.")
else:
  print("No, 'firstname' is not a key in the dictionary.")

Output:

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

 

 

Add Elements in a Dictionary

New elements can be added in a dictionary be assigning a value to a new key using assignment operator =. New key should be unique since Python dictionary does not support duplicate keys.

 

#Python program to exemplify addition of an element in a dictionary

info = {
   "name": "Victor",
   "age": 23,
   "city": "California"
}
print(info)
info["gender"]="Male"
print(info)

Output:

{'name': 'Victor', 'age': 23, 'city': 'California'}
{'name': 'Victor', 'age': 23, 'city': 'California', 'gender': 'Male'}

 

 

Delete Elements of a Dictionary

Several ways to delete elements from a dictionary are:

  • pop() – deletes the mentioned key inside the function as an argument and its value from the dictionary
  • popitem() – deletes last key-value pair from the dictionary but last is not clearly defined since elements of a dictionary are unordered.
  • clear() – deletes all key-value pairs from the dictionary
  • del – deletes the dictionary itself or a key-value pair of the dictionary
# Python program to exemplify deletion of elements of a dictionary

info = {
   "name": "Brandon",
   "age": 22,
   "city": "Las Vegas"
}
info.pop("city")
print(info)

info = {
   "name": "Brandon",
   "age": 22,
   "city": "Las Vegas"
}
info.popitem()
print(info)

info = {
    "name": "Brandon",
   "age": 22,
   "city": "Las Vegas"
}
info.clear()
print(info)

info = {
    "name": "Brandon",
   "age": 22,
   "city": "Las Vegas"
}
del info["city"]
print(info)
del info
print(info)

Output:

{'name': 'Brandon', 'age': 22}
{'name': 'Brandon', 'age': 22}
{}
{'name': 'Brandon', 'age': 22}
Traceback (most recent call last):
  File "main.py", line 35, in <module>
    print(info)
NameError: name 'info' is not defined

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *