Python Dictionary

A Dictionary in Python is a collection data type which is unordered, mutable and indexed. In Python, dictionaries are written with curly brackets { }, and store key-value pairs.

  • Dictionary keys should be the immutable Python object, for example, number, string, or tuple. Keys are case sensitive. Duplicate keys are not allowed in the dictionary.
  • Dictionary values can be of any type (mutable also) such as list, tuple, integer, etc.

Python dictionaries are very much similar to HashTable in Java.

1. Creating the Dictionary

1.1. With curly braces

The syntax for creating a dictionary is simple. The dictionary should have multiple key-value pairs enclosed in curly braces { }. Each key is separated with its value with a color ( : ) sign.

The syntax to define the dictionary is given below:

# an empty dictionary
Dict = {}

# a dictionary with 3 items
Dict = {
	"Name": "Lokesh",
	"Age": 39,
	"Blog": "howtodoinjava"
}

print(Dict)

Program output.

{'Age': 39, 'Name': 'Lokesh', 'Blog': 'howtodoinjava'}

1.2. With dict() constructor

Python provides the built-in function dict() which can be used to create a dictionary.

# Creating a Dictionary with dict() method
Dict = dict({1: 'Python', 2: 'Example'})
print(Dict)
 
# Creating a Dictionary with tuples
Dict = dict([(1, 'Python'), (2, 'Example')])
print(Dict)

# Notice that the keys are not the string literals
Dict = dict(firstName="Lokesh", lastName="Gupta", age=39)
print(Dict)

Program output.

{1: 'Python', 2: 'Example'}
{1: 'Python', 2: 'Example'}
{'firstName': 'Lokesh', 'lastName': 'Gupta', 'age': 39}

2. Accessing the Values

To get a value from the python dictionary, we can pass the key to the dictionary in two ways:

  • Using dictionary with square brackets i.e. Dict[key]
  • Using dictionary’s get() method i.e. Dict.get(Key). The get() method allows us to provide a default value incase the key is not found in the dictionary.

Both approaches give the same result.

Dict = {
  "name":"Lokesh",
  "blog":"howtodoinjava",
  "age":39
}

print( Dict["name"] )
print( Dict.get("age") )

print( Dict.get("country") )
print( Dict.get("country", "India") )

Program output.

Lokesh
39
None
India

3. Check if a key exist in Dictionary

We can determine if a given key is present in the dictionary or not by using the in operator.

3.1. key in Dict

Python program to use in operator to check if a key is available in the dictionary.

Dict = {
  "name":"Lokesh",
  "blog":"howtodoinjava",
  "age":39
}

if "name" in Dict:
  print("name is present")
else:
  print("name is not present")

Program output.

name is present

3.2. key not in Dict

Python program to use in operator to check if a key is not present in the dictionary.

Dict = {
  "name":"Lokesh",
  "blog":"howtodoinjava",
  "age":39
}

if "country" not in Dict:
  print("country is not present")
else:
  print("country is present")

Program output.

country is not present

4. Adding / Updating the Values

To update a value into the dictionary, there are two ways:

  • Using the syntax Dict[key] = value
  • Using dictionary’s update() method i.e. Dict.update( {Key: Value} )
Dict = {
  "name":"Lokesh",
  "blog":"howtodoinjava",
  "age":39
}
print( Dict["name"] )

#Updating the name
Dict["name"] = "Alex"
print( Dict["name"] )

#Updating the name with update() method
Dict.update({"name": "Brian"})
print( Dict["name"] )

#Adding a new item - country
Dict.update({"country": "India"})
print( Dict["country"] )

Program output.

Lokesh
Alex
Brian
India

5. Deleting Dictionary Items

5.1. Using del keyword

The items of the python dictionary can be deleted by using the del keyword.

Dict = {
  "name":"Lokesh",
  "blog":"howtodoinjava",
  "age":39
}
print( Dict )

#Deleting the name
del Dict["name"]
print( Dict )

#Deleting the dictionary
del Dict
print( Dict )

Program output.

{'name': 'Lokesh', 'blog': 'howtodoinjava', 'age': 39}
{'blog': 'howtodoinjava', 'age': 39}

Traceback (most recent call last):
  File "<string>", line 14, in <module>
NameError: name 'Dict' is not defined

5.2. Using pop() method

The pop() method has similar effect to the dictionary as the del keyword, for removing the items from the dictionary.

Dict = {
  "name":"Lokesh",
  "blog":"howtodoinjava",
  "age":39
}
print( Dict )

#Deleting the name
Dict.pop("name")
print( Dict )

Program output.

{'name': 'Lokesh', 'blog': 'howtodoinjava', 'age': 39}
{'blog': 'howtodoinjava', 'age': 39}

5.3. Using clear() method

The clear() method removes all the items from the dictionary. The clear() method returns an empty directory.

Dict = {
  "name":"Lokesh",
  "blog":"howtodoinjava",
  "age":39
}
print( Dict )

#Clear all the dictionary items
Dict.clear()
print( Dict )

Program output.

{'name': 'Lokesh', 'blog': 'howtodoinjava', 'age': 39}
{}

6. Iterating over Dictionary Items

We can iterate over a dictionary items in the following ways:

6.1. Using for loop

Python program to iterate over dictionary items and print the keys and values.

Dict = {
  "name":"Lokesh",
  "blog":"howtodoinjava",
  "age":39
}

for k in Dict:
  v = Dict[k]
  print("Key :" + k + ", Value: " + str(v))

Program output.

Key :name, Value: Lokesh
Key :blog, Value: howtodoinjava
Key :age, Value: 39

6.2. Iterate all values using values() method

Python program to iterate over all the values in the dictionary using values() method.

Dict = {
  "name":"Lokesh",
  "blog":"howtodoinjava"
}

for v in Dict.values():
  print("Value :" + v)

Program output.

Value :Lokesh
Value :howtodoinjava

6.3. Iterate all key-value pairs using items() method

Python program to iterate over all the keys and the values in the dictionary using items() method.

Dict = {
  "name":"Lokesh",
  "blog":"howtodoinjava"
}

for i in Dict.items():
  print(i)
  print("Key :" + i[0] + ", Value: " + i[1])

Program output.

('name', 'Lokesh')
Key :name, Value: Lokesh

('blog', 'howtodoinjava')
Key :blog, Value: howtodoinjava

7. Built-in Dictionary Methods

Python has these built-in functions that we can use on dictionaries.

7.1. clear()

The clear() method removes all the elements from the dictionary.

Dict = {"name":"Lokesh", "blog":"howtodoinjava"}
Dict.clear()
print(Dict)

Program output.

{} # empty dictionary

7.2. copy()

The copy() method returns a shallow copy of the dictionary.

Dict = {"name":"Lokesh", "blog":"howtodoinjava"}
myDict = Dict.copy()
print(myDict)

Program output.

{'name': 'Lokesh', 'blog': 'howtodoinjava'}

7.3. fromkeys()

The fromkeys() method returns a dictionary with the specified keys and value.

keys = ('key1', 'key2', 'key3')
value = 0

Dict = dict.fromkeys(keys, value)

print(Dict)

Program output.

{'key1': 0, 'key2': 0, 'key3': 0}

7.4. get()

The get() method returns the value of the specified key.

Dict = {"name":"Lokesh", "blog":"howtodoinjava"}

print(Dict.get("name"))

Program output.

Lokesh

7.5. items()

The items() method returns a list containing a tuple for each key value pair.

Dict = {"name":"Lokesh", "blog":"howtodoinjava"}

print(Dict.items())

for i in Dict.items():
  print(i)

Program output.

dict_items([('name', 'Lokesh'), ('blog', 'howtodoinjava')])

('name', 'Lokesh')
('blog', 'howtodoinjava')

7.6. keys()

The keys() method returns a list containing the dictionary’s keys.

Dict = {"name":"Lokesh", "blog":"howtodoinjava"}

print(Dict.keys())

for i in Dict.keys():
  print(i)

Program output.

dict_keys(['name', 'blog'])

name
blog

7.7. pop()

The pop() method removes the element with the specified key.

Dict = {"name":"Lokesh", "blog":"howtodoinjava"}

Dict.pop("name")
print(Dict)

Program output.

{'blog': 'howtodoinjava'}

7.8. popitem()

The popitem() method removes the last inserted key-value pair as tuple. In versions before 3.7, the popitem() method removes a random item.

Dict = {"name":"Lokesh", "blog":"howtodoinjava"}

x = Dict.popitem()
print(x)

Program output.

('blog', 'howtodoinjava')

7.9. setdefault()

The setdefault() method returns the value of the specified key.

If the specified key does not exist in the dictionary, the method inserts the key, with the specified value.

Dict = {"name":"Lokesh", "blog":"howtodoinjava"}

Dict.setdefault("age", "39")
print(Dict)

Program output.

{'name': 'Lokesh', 'blog': 'howtodoinjava', 'age': '39'}

7.10. update()

The update() method updates the dictionary with the specified key-value pairs.

Dict = {"name":"Lokesh", "blog":"howtodoinjava"}

Dict.update({"name": "Alex"})
print(Dict)

Program output.

{'name': 'Alex', 'blog': 'howtodoinjava'}

7.11. values()

The update() method returns a list of all the values in the dictionary.

Dict = {"name":"Lokesh", "blog":"howtodoinjava"}

print(Dict.values())

for v in Dict.values():
  print(v)

Program output.

dict_values(['Lokesh', 'howtodoinjava'])
Lokesh
howtodoinjava

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode